将php中的字符串拆分为地址和电话号码(移动和传真)

:)

I am trying to split a string that is made of a street address and two phone numbers.

This is the var_dump of the variable $string

string(74) " Via Alsazia 3 Scala A Int 1 35127 PADOVA (PD) 049 774266 049 775756 "

I tried this to split each one piece with this code:

$split = preg_split(')', $string);
$address = $split[0];
$split_two =preg_split(' ' ,  $split[1]);
$fax = $split_two[0];
$mobile = $split_two[1];

but it gives me only this

V

Is there any way to do this ?

One way to do it without regex:

$parts = explode(' ',$str);
$phone1 = array_pop($parts);
$phone1 = array_pop($parts)." ".$phone1;
$phone2 = array_pop($parts);
$phone2 = array_pop($parts)." ".$phone2;

.. assumes the phone numbers are always in the same format.

here's a fiddle: https://3v4l.org/Qp0kS

you definitely need to enable warnings display

anyway, to fix you problem you can try:

<?php
$string = " Via Alsazia 3 Scala A Int 1 35127 PADOVA (PD) 049 774266 049 775756 ";

$split = explode(')', trim($string)); // note trim and explode
$address = $split[0];
$split_two = explode(' ' ,  trim($split[1])); // note trim
$fax = $split_two[0].' '.$split_two[1]; // note indexes
$mobile = $split_two[2].' '.$split_two[3]; // note indexes

echo 'fax '.$fax."<br>
";
echo 'mobile '.$mobile."<br>
";
?>

another variant is:

<?php
$string = " Via Alsazia 3 Scala A Int 1 35127 PADOVA (PD) 049 774266 049 775756 ";

preg_match('/^([^\)]+)\) +(\d+ \d+) +(\d+ \d+)$/', trim($string), $matches);

$address = $matches[1];
$fax = $matches[2];
$mobile = $matches[3];

echo 'address '.$address."<br>
";
echo 'fax '.$fax."<br>
";
echo 'mobile '.$mobile."<br>
";
?>

You can try to use below regex

(.*?)(\d{3}\s\d{6})\s(\d{3}\s\d{6})$

First group lazy matches any characters - it is the address

Second and third groups match phone numbers at the end of the line in the following format:

3-digit-number space 6-digits-number