phpcoderx
phpcoderx

Reputation: 570

php regular expression for extracting a phone number

I need help with php regular expression. I have a $text variable. For example:"foo foo random words Caller Phone:+922432202229 random words foo words" I want to extract 922432202229 from $text. Please Note that the $text could contains other similar numbers too,so I just want the number which comes right after "Caller Phone :" Here is what I tried:

    $matches = array();
    preg_match_all("/Caller Phone : +[0-9]{12}$/", $text, $matches);
    $matches = $matches[0];

Upvotes: 0

Views: 120

Answers (3)

Jahanzeb
Jahanzeb

Reputation: 613

You can use this code

    $matches = array();
    preg_match_all("/Caller Phone:\+\d{12}/i", $text, $matches);
    $matches = $matches[0];

If you have this data in $text variable

$text = "foo foo random words Caller Phone:+922432202229 random words foo words";

It will show this result on the your given data

Array
(
    [0] => Array
    (
        [0] => Caller Phone:+922432202229
    )

)

Upvotes: 0

x4rf41
x4rf41

Reputation: 5337

this should be more flexible and safe:

$matches = array();
preg_match_all('/Caller Phone\s*:\s*\(+|)([0-9]{8,12})/i', $text, $matches);
$phones = $matches[2];

Upvotes: 0

Luceos
Luceos

Reputation: 6720

You will need to collect the actual value behind Phone: by using the (), like so:

preg_match_all("/Caller Phone : ([0-9]+)$/", $text, $matches);

I also changed {12} to + so you also have all numbers as long as it will go on. Validation must go afterwards then.

Only by using () you will have values be returned to your $matches variable.

Upvotes: 1

Related Questions