PHP拆分名称和电话号码(文字和数字)

时间:2018-06-28 08:41:49

标签: php regex preg-split

我正在使用preg_split从字符串中分离文本和电话号码。

我的以下测试用例:

$string_one = "1. Maria +60136777000";
$string_two = "2. Rahul Khan 0146067705";
$string_three = "Johny +6013699900";
$string_four = "Henry 01363456900";

这是我的功能:

function split_them($str) {
    return preg_split("/(\D)(\d)/", $str);
}

当我使用这种功能时,电话号码总是不完整:

// string_one
echo "<pre>";
print_r(split_them($string_one));
echo "</pre>";

// output
array(2
0   =>  1. Maria 
1   =>  0136777000 // <--- number is incomplete
)

// string_two
echo "<pre>";
print_r(split_them($string_two));
echo "</pre>";

// output
array(2
0   =>  2. Rahul Khan
1   =>  146067705 // <--- number is incomplete
)

// string_three
echo "<pre>";
print_r(split_them($string_three));
echo "</pre>";

// output
array(2
0   =>  Johny
1   =>  013699900 // <--- number is incomplete
)

// string_four
echo "<pre>";
print_r(split_them($string_four));
echo "</pre>";

// output
array(2
0   =>  Henry
1   =>  1363456900 // <--- number is incomplete
)

也许我的正则表达式不正确。我想念什么?

4 个答案:

答案 0 :(得分:1)

或类似这样:

function split_them($str) {
    preg_match("/(.+)\s+(.?\d{5,})/", $str, $matches);
    array_shift($matches);
    return $matches;
}

输出为:

  

数组(       [0] => 1.玛丽亚       [1] => +60136777000)

     

数组(       [0] => 2. Rahul Khan       [1] => 0146067705)

     

数组(       [0] =>约翰尼       [1] => +6013699900)

     

数组(       [0] =>希特勒       [1] => 01363456900)

答案 1 :(得分:1)

我建议使用以下preg_split代码:

preg_split('~\s+(?=\+?\d+$)~', $s)

请参见PHP demo

它在最后一个1+个空格(\s+)处拆分字符串,后跟一个可选的+\+?)和1+个数字(\d+)字符串($的末尾。

{{3}}:

$re = '/\s+(?=\+?\d+$)/';
$strs = ['Johny +6013699900','2. Rahul Khan 0146067705','Johny +6013699900','Henry 01363456900'];
foreach ($strs as $s) {
    print_r(preg_split($re, $s));
}

输出:

Array
(
    [0] => Johny
    [1] => +6013699900
)
Array
(
    [0] => 2. Rahul Khan
    [1] => 0146067705
)
Array
(
    [0] => Johny
    [1] => +6013699900
)
Array
(
    [0] => Henry
    [1] => 01363456900
)

答案 2 :(得分:0)

  • 尝试$ iparr = split(“ / + /”,$ ip);打印“ $ iparr [0]”;

答案 3 :(得分:-1)

尝试使用explode()PHP函数按字符串拆分它们。 例子

$foo = "one two three";

print_r(explode(" ", $foo));

//Output
array (
0 => 'one',
1 => 'two',
2 => 'three'
)