我需要从一小段文本中提取一组预定义的主题标签,然后提取紧随其后的数字(如果有)。例如。我需要从“使用#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);
替换*
为+
因为
*
匹配零次或多次。
+
匹配一次或多次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句