Swarne27
Swarne27

Reputation: 5747

Need to extract the phone number within the string

I have a string like the following which can change every time.

style="margin: 0;">\r\n
Phone\r\n </p>\r\n <p style="font-weight: bold; margin: 0;">\r\n 0411313062\r\n </p>\r\n
</td>\r\n
</tr>\r\n
<tr>\r\n
<td style="padding-bottom: 18px;">\r\n

I need to extract the phone number 0411313062 out of this string.

Upvotes: 0

Views: 1609

Answers (3)

ganaa
ganaa

Reputation: 167

this code works fine. Try this

$tab = <<<EOD
style="margin: 0;">\r\n Phone\r\n </p>\r\n <p style="font-weight: bold;   margin: 0;">\r\n 0411313062\r\n </p>\r\n </td>\r\n
 </tr>\r\n
 <tr>\r\n
<td style="padding-bottom: 18px;">\r\n) EOD;


$input= explode("\r\n", $tab);
print_r($input);

the phone number is

echo $input[4];

Upvotes: 0

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Try this

preg_match('\(?([0-9]{3})\s*\)?\s*-?\s*([0-9]{3})\s*-?\s*([0-9]{4})', $string, $match );

See it in action,

https://regex101.com/r/pLqDWw/3

This will match 7 or 10 digit phone numbers with or without the - or (area code) such as 800-555-5555 or 8005555555 or (800)555-5555 or 555-5555 etc

If you have to match more then one number, I would suggest using something like PHPQuery, to refine the text ( html ) you are searching for it against. You could try something simpler like, preg_match_all but once you get the hang of PHPQuery you'll thank me.

Upvotes: 1

Suchit kumar
Suchit kumar

Reputation: 11869

You can try this:

$text = 'style="margin: 0;">\r\n
Phone\r\n </p>\r\n <p style="font-weight: bold; margin: 0;">\r\n 0411313062\r\n </p>\r\n
</td>\r\n
</tr>\r\n
<tr>\r\n
<td style="padding-bottom: 18px;">\r\n';
preg_match("/[0-9]{10}/", $text, $matches);// in case of multiple occurrences us preg_match_all
print_r($matches[0]);//0411313062

Upvotes: 1

Related Questions