I want to preg_match number "20,956" from $url1 and number "2,894,865" from $url2
$url1:
<meta name="description" content="‎ST. Eye Clinic - عيادة دكتور محمد عزب لطب و جراحة العيون‎, Dumyat Al Jadidah, Dumyat, Egypt. 20,956 visits ·
$url2:
<meta name="description" content="ABC. 2,894,865 visits ·
Tried this to work for both of urls, it works for only $url1 but not in $url2
$p = preg_match("'Egypt. (.*?) visits'si", $url, $matches);
$p2 = preg_replace("/[^0-9]/", "", $matches[1]);
print $p2;
Any Idea to make it work for both $url1&2?
CodePudding user response:
You can use
if (preg_match('~\d[,\d]*(?=\s*visits)~', $url, $matches)) {
echo $matches[0];
}
See the regex demo. Details:
\d
- a digit[,\d]*
- zero or more commas/digits(?=\s*visits)
- a positive lookahead that requires zero or more whitespaces and thenvisits
string immediately to the right of the current location.
See a PHP demo:
$urls = ['<meta name="description" content="‎ST. Eye Clinic - عيادة دكتور محمد عزب لطب و جراحة العيون‎, Dumyat Al Jadidah, Dumyat, Egypt. 20,956 visits ·',
'<meta name="description" content="ABC. 2,894,865 visits ·'];
foreach ($urls as $url) {
if (preg_match('~\d[,\d]*(?=\s*visits)~', $url, $matches)) {
echo $matches[0] . PHP_EOL;
}
}
Output:
20,956
2,894,865