Reputation: 1669
I am looking for a php/regex solution to get the phone extension from the data examples listed below.
+49 (0) 1111 807 111 (Ext 1012)
+49 (0) 1111 807 111 (Ext1012)
+49 (0) 1111 807 111 [Ext 1012]
+49 (0) 2222 807 111 <Ext 1012>
+49 (0) 2222 807 111 <Ext1012>
+49 (0) 2222 807 111 <1012>
+49 (0) 2222 807 111 [1012]
Any help would be appreciated.
Upvotes: 0
Views: 172
Reputation: 4523
You can use the following regex (using positive lookahead / lookbehind) to get all the extensions from the phone numbers :
(?<=\d{3}\s[\(\[<]).*?(?=\)|\]|>)
input >> +49 (0) 1111 807 111 (Ext 1012)
regex search >> (?<=\d{3}\s[\(\[<]).*?(?=\)|\]|>)
output >> Ext 1012
PHP
$re = '/(?<=\d{3}\s[\(\[<]).*?(?=\)|\]|>)/';
$str = '+49 (0) 1111 807 111 (Ext 1012)
+49 (0) 1111 807 111 (Ext1012)
+49 (0) 1111 807 111 [Ext 1012]
+49 (0) 2222 807 111 <Ext 1012>
+49 (0) 2222 807 111 <Ext1012>
+49 (0) 2222 807 111 <1012>
+49 (0) 2222 807 111 [1012]';
preg_match_all($re, $str, $matches);
print_r($matches);
Upvotes: 1
Reputation: 2302
Don't need regex if the first set of characters is always the same. Get the length of the string and get the first 21 characters of that (spaces included up to the extension start). Figure out how many positions make up the extension and substring from that.
Example of what I mean:
+49 (0) 1111 807 111 (Ext 1012)
say thats $string = "+49 (0) 1111 807 111 (Ext 1012)";
$length = strlen($string) will give you 31.
Remove up to the extension gives you to 20 (position 19 being the space. So anything from 21-30 is the extension.
echo $string[21].$string[22].$string[23].....$string[30];
or you could use substr and get the ending positions. Use - to go in reverse counting from 1.
echo substr($string,-5,-1);
Upvotes: 2
Reputation: 14941
You could try this:
/(\(Ext|(\[|<)(Ext)?)\s*(\d+)(\)|>|])/
The first part will capture:
$phones = '
+49 (0) 1111 807 111 (Ext 1012)
+49 (0) 1111 807 111 (Ext1012)
+49 (0) 1111 807 111 [Ext 1012]
+49 (0) 2222 807 111 <Ext 1012>
+49 (0) 2222 807 111 <Ext1012>
+49 (0) 2222 807 111 <1012>
+49 (0) 2222 807 111 [1012]
';
preg_match_all('/(\(Ext|(\[|<)(Ext)?)\s*(\d+)(\)|>|])/', $phones, $matches);
The var_dump
of $matches would give you an array and you are interested in the 4th capture group.
array(7) {
[0]=> string(4) "1012"
[1]=> string(4) "1012"
[2]=> string(4) "1012"
[3]=> string(4) "1012"
[4]=> string(4) "1012"
[5]=> string(4) "1012"
[6]=> string(4) "1012"
}
Upvotes: 1
Reputation: 606
echo part of the string from -5 to -1
echo substr($number, -5, -1);
for '+49 (0) 1111 807 111 (Ext 1012)', it returns '1012'
Upvotes: 2