Home > Back-end >  preg_match string from meta name
preg_match string from meta name

Time:11-22

I want to preg_match number "20,956" from $url1 and number "2,894,865" from $url2

$url1:

<meta name="description" content="&#x200e;ST. Eye Clinic - &#x639;&#x64a;&#x627;&#x62f;&#x629; &#x62f;&#x643;&#x62a;&#x648;&#x631; &#x645;&#x62d;&#x645;&#x62f; &#x639;&#x632;&#x628; &#x644;&#x637;&#x628; &#x648; &#x62c;&#x631;&#x627;&#x62d;&#x629; &#x627;&#x644;&#x639;&#x64a;&#x648;&#x646;&#x200e;, Dumyat Al Jadidah, Dumyat, Egypt. 20,956 visits &#xb7;

$url2:

<meta name="description" content="ABC. 2,894,865 visits &#xb7;

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 then visits string immediately to the right of the current location.

See a PHP demo:

$urls = ['<meta name="description" content="&#x200e;ST. Eye Clinic - &#x639;&#x64a;&#x627;&#x62f;&#x629; &#x62f;&#x643;&#x62a;&#x648;&#x631; &#x645;&#x62d;&#x645;&#x62f; &#x639;&#x632;&#x628; &#x644;&#x637;&#x628; &#x648; &#x62c;&#x631;&#x627;&#x62d;&#x629; &#x627;&#x644;&#x639;&#x64a;&#x648;&#x646;&#x200e;, Dumyat Al Jadidah, Dumyat, Egypt. 20,956 visits &#xb7;',
    '<meta name="description" content="ABC. 2,894,865 visits &#xb7;'];
foreach ($urls as $url) {
  if (preg_match('~\d[,\d]*(?=\s*visits)~', $url, $matches)) {
    echo $matches[0] . PHP_EOL;
  }
}

Output:

20,956
2,894,865
  • Related