0

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.

3
  • What do you have so far? And can the +, / and - characters appear in the text as well? Commented May 18, 2013 at 17:18
  • Describe what kind of strings may be accepted as phone numbers. Commented May 18, 2013 at 17:19
  • in the href- tag final numbers must not have () round brackets.preg_match_all('~^(.*?)(\d+)~m', $string, $matches); foreach ($matches[1] as $k => $text) { $int = $matches[2][$k]; echo "$text => $int\n"; } Commented May 18, 2013 at 17:36

2 Answers 2

0

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);
Sign up to request clarification or add additional context in comments.

2 Comments

no. one problem: doesnt work when there are more (white)-spaces. -thanks. till.
more? where? you can change the regex adding more \s* where are expected more spaces...
0

Instead of preg_split following preg_match might work:

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.