Search code examples
phppreg-split

PHP preg-split text-string telephone-numbers


please help me with the following problem:

    $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';

what i need is something like this:

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


)

and the final output :

<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>

thanks for helping! till.


Solution

  • The preg_replace does all the job for you. Adapt the REGEX on first parameter following this sintax to more variations.

    <?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);