[英]php preg_match_all simple regex returns empty values
我需要从一小段文本中提取一组预定义的主题标签,然后提取紧随其后的数字(如果有)。 例如。 我需要从“使用#other30主题标签测试字符串”中提取30。 我认为preg_match_all是正确的选择。
一些测试代码:
$hashtag = '#other';
$string = 'Test string with #other30 hashtag';
$matches = [];
preg_match_all('/' . $hashtag . '\d*/', $string, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => #other30
)
)
完美...按预期工作。 现在提取数字:
$string = $matches[0][0]; // #other30
$matches = [];
preg_match_all('/\d*/', $string, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] => 30
[7] =>
)
)
什么? 看起来它正在尝试匹配每个字符?
我知道一些与preg_match_all相关的答案( 一个 , 两个 ),但是它们都使用带括号的子模式。 根据文档-这是可选的。
我想念什么? 我如何简单地将所有匹配项放入与/ \\ d * /这样的基本正则表达式匹配的数组中,似乎在php中似乎没有更合适的功能。
我从没想过我会用PHP这样的基本知识来挠头。 非常感激。
您需要更换:
preg_match_all('/\d*/', $string, $matches);
有:
preg_match_all('/\d+/', $string, $matches);
替换*
与+
因为
*
匹配零次或多次。
+
匹配一次或多次。
您可以使用捕获组:
preg_match_all('/' . $hashtag . '(\d*)/', $string, $matches);
echo $matches[1][0] . "\n";
//=> 30
这里(\\d*)
将捕获$hashtag
之后的数字。
另请参见,您可以使用\\K
在特定点之后重置以获取匹配的一部分。 当然,需要使用\\d+
而不是\\d*
来匹配一个或多个数字。 否则, 在零个 或多个数字匹配的字符之间的间隙中将存在匹配项 。
因此您的代码可以简化为
$hashtag = '#other';
$string = 'Test string with #other30 #other31 hashtag';
preg_match_all('/' . $hashtag . '\K\d+/', $string, $matches);
print_r($matches[0]);
请参阅eval.in上的演示,并考虑对$hashtag
使用preg_quote 。
<?php
$hashtag = '#other';
$string = 'Test string with #other30 hashtag';
$matches = [];
preg_match_all('/' . $hashtag . '\d*/', $string, $matches);
$string = preg_match_all('#\d+#', $matches[0][0], $m);
echo $m[0][0];
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.