2013-05-18 32 views
0

請幫我下面的問題: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'; 

我需要的是這樣的:

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> 

感謝您的幫助! 直到。

+0

到目前爲止你有什麼?文本中還可以出現「+」,「/'和」-'字符嗎? – jeroen

+0

描述什麼樣的字符串可以被接受爲電話號碼。 –

+0

在href-標籤最後的數字中不能有()括號括起來的一個括號('〜^(。*?)(\ d +)〜m',$ string,$ matches); foreach($ matches [1]爲$ k => $ text){ $ int = $ matches [2] [$ k]; echo「$ text => $ int \ n」; } – user1824042

回答

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); 
+0

究竟需要什麼!非常感謝!直到。 – user1824042

+0

沒有。一個問題:當有更多(白色)空間時不起作用。 -謝謝。直到。 – user1824042

+0

更多?哪裏?你可以改變正則表達式添加更多'\ s *'在哪裏預計更多的空間... –

0

而不是使preg_split以下的preg_match可能的工作:

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

OUTPUT:

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 
)