简体   繁体   English

元名称中的 preg_match 字符串

[英]preg_match string from meta name

I want to preg_match number "20,956" from $url1 and number "2,894,865" from $url2我想 preg_match 来自 $url1 的数字“20,956”和来自 $url2 的数字“2,894,865”

$url1: $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: $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试过这对两个网址都有效,它只适用于 $url1 但不适用于 $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?有什么想法让它同时适用于 $url1&2 吗?

You can use您可以使用

if (preg_match('~\d[,\d]*(?=\s*visits)~', $url, $matches)) {
  echo $matches[0];
}

See the regex demo .请参阅正则表达式演示 Details :详情

  • \d - a digit \d - 一个数字
  • [,\d]* - zero or more commas/digits [,\d]* - 零个或多个逗号/数字
  • (?=\s*visits) - a positive lookahead that requires zero or more whitespaces and then visits string immediately to the right of the current location. (?=\s*visits) - 一个正向前瞻,需要零个或多个空格,然后立即visits当前位置右侧的字符串。

See a PHP demo :请参阅PHP 演示

$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: Output:

20,956
2,894,865

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM