PHP preg-split文本字符串电话号码

时间:2013-05-18 17:14:08

标签: php preg-split

请帮我解决以下问题:

    $my_string = 'here is some text and my number: +43 (0) 123 456 - 78 and 
    some more text and a different number + 43(0) 1234/ 567-789 and 
    a final text';

我需要的是这样的事情:

Array
(
    [0] => here is some text and my number:

    [1] => +43 (0) 123 456 - 78

    [2] => and some more text and a different number

    [3] => + 43(0) 1234/ 567-789

    [4] => and a final text


)

和最终输出:

<span>
here is some text and my number:
<a href="tel:+43 123 456 78">+43 (0) 123 456 - 78</a>
and some more text and a different number
<a href="tel:+43 1234 567 789">+ 43(0) 1234/ 567-789</a>
and a final text
</span>

感谢您的帮助! 为止。

2 个答案:

答案 0 :(得分:0)

而不是在preg_match之后的preg_split可能有效:

if(preg_match('#([\w\s:]+)([/+\d\s()-]+)([\w\s:]+)([/+\d\s()-]+)([\w\s:]+)#', $str, $m))
   print_r($m);

<强>输出:

Array
(
    [0] => here is some text and my number: +43 (0) 123 456 - 78 and 
    some more text and a different number + 43(0) 1234/ 567-789 and 
    a final text
    [1] => here is some text and my number: 
    [2] => +43 (0) 123 456 - 78 
    [3] => and 
    some more text and a different number 
    [4] => + 43(0) 1234/ 567-789 
    [5] => and 
    a final text
)

答案 1 :(得分:0)

preg_replace为你完成所有工作。在this sintax之后的第一个参数上调整REGEX以适应更多变化。

<?php

$my_string = 'here is some text and my number: +43 (0) 123 456 - 78 and
    some more text and a different number + 43(0) 1234/ 567-789 and
    a final text';

$output = preg_replace("/(\+\s*([0-9]+)\s*\(\s*([0-9]+)\s*\)\s*([0-9]+)[ \/-]+([0-9]+)[ \/-]+([0-9]+))/","<a href=\"tel:+$2 $4 $5 $6\">$1</a>",$my_string);

var_dump($output);