Reputation: 1722
So I have this list of strings given to me as follows:
David palmer & Betsy Harrell 229-548-9651 Emily
I know how to get the phone number out of that string by doing this:
preg_match_all('/[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];
But I need to get the name before hand AND the phone number. This is a bit beyond my regex knowledge. So I need
David palmer & Betsy Harrell
and
229-548-9651
Upvotes: 1
Views: 65
Reputation: 627110
Use capturing groups to get two substrings:
$s = 'David palmer & Betsy Harrell 229-548-9651 Emily';
if (preg_match('~^(.*?)\s*(\d{3}-\d{3}-\d{4})~', $s, $m)) {
echo $m[1] . "\n" . $m[2];
}
See PHP demo.
Pattern details:
^
- start of string(.*?)
- any 0+ chars other than line break chars as few as possible up to the first...\s*
- 0+ whitespaces(\d{3}-\d{3}-\d{4})
- date pattern (3 digits, -
, 3 digits, -
, 4 digits).Note you do not need to put -
into a character class, and no need to escape it outside a character class. \d
is equal to [0-9]
if you do not use any specific modifiers/PCRE verbs related to Unicode.
Upvotes: 1