gpt4 book ai didi

php preg_match_all 简单的正则表达式返回空值

转载 作者:行者123 更新时间:2023-12-04 02:16:08 26 4
gpt4 key购买 nike

我需要从文本 block 中提取一组预定义的主题标签,然后提取紧随其后的数字(如果有)。例如。我需要从“带有#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 相关的答案( onetwo ),但它们都使用带括号的子模式。根据文档 - 它是可选的。

我错过了什么?我如何简单地将所有匹配项放入一个数组中,以匹配这样一个基本的正则表达式,如/\d*/在 php 中似乎没有更合适的函数。

我从没想过我会为 PHP 中如此基础的东西挠头。非常感谢。

最佳答案

你需要替换:

preg_match_all('/\d*/', $string, $matches);

与:

preg_match_all('/\d+/', $string, $matches);

+替换*

因为

* Match zero or more times.

+ Match one or more times.

关于php preg_match_all 简单的正则表达式返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33542486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com