Could you help me to do this: I have a text in which there is a 9 digit number and I need to extract it to store it in a variable, the number always starts 9
Example of the text string :
Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum.
Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec nisi sed elit malesuada tempor.
The numbers I need always start with the initial 9 and are not always in the position 1 or 2 is random, the code I am using is the following :
$str = "Lorem...";
$pattern = '/[0-9]{9}/';
if (preg_match($pattern, $str, $matches)){
echo $matches[0];
}
The result I get is the following: 123456789 The correct one would be: 980202301
CodePudding user response:
You can use
(?<!\d)9\d{8}(?!\d)
See the regex demo. Details:
(?<!\d)- no digit immediately to the left is allowed9- a9char\d{8}- any either digits(?!\d)- no digit immediately to the right is allowed.
See also a PHP demo:
$str = 'Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum.
Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec nisi sed elit malesuada tempor.';
$pattern = '/(?<!\d)9\d{8}(?!\d)/';
if (preg_match_all($pattern, $str, $matches)){
print_r($matches[0]);
}
Output:
Array
(
[0] => 980202301
)
CodePudding user response:
you can change your pattern so it matches numbers starting with 9
$pattern = '/9[0-9]{8}/'
CodePudding user response:
You might also use word boundaries \b to prevent a partial word match, and match 9 and 8 digits.
Note that preg_match will only find the first match, if you want all matches use preg_match_all.
\b9\d{8}\b
$str = 'Lorem ipsum dolor sit amet, consectetur. Integer ac tempor 123456789, et semper arcu. Maecenas vitae enim sed tortor 980202301 venenatis commodo. Fusce tincidunt volutpat bibendum. Cras vehicula ligula at urna vestibulum condimentum.
Praesent non blandit 45678910911, sed porta nulla. Phasellus eleifend, metus in consequat dictum, arcu nibh accumsan dolor, eget tristique eros massa et nisl. Anexo 4577 Phasellus congue consequat ante, nec nisi sed elit malesuada tempor.';
$pattern = '/\b9\d{8}\b/';
if (preg_match($pattern, $str, $matches)){
echo $matches[0];
}
Output
980202301
