括号中特定ID的正则表达式

对于正则表达式,我几乎没有信心。用PHP代码编写。

我需要能够过滤出遵循这种格式的字符串,其中数字可以是4到6位数字(仅数字):

$input = "This is my string with a weird ID added cause I'm a weirdo! (id:11223)";

我可以通过strrpos();查找空格的最后一个位置来删除最后一个单词(似乎它们都没有来自JSON提要的尾随空格),然后使用substr();进行剪切。但是我认为更优雅的方式是子字符串。预期的输出将是:

$output = trim(preg_replace('[regex]',$input));
// $output = "This is my string with a weird ID added cause I'm a weirdo!"

因此,此正则表达式应与方括号,id:部分以及任何连续的数字匹配,例如:

(id:33585)
(id:1282)
(id:9845672)

打算使用preg_replace()函数将其从数据Feed中删除。不要问我为什么他们决定在描述字符串中包含ID。这也让我感到惊讶,为什么它不是JSON提要中的一个单独的列。

coffee3582 回答:括号中特定ID的正则表达式

尝试使用模式\(id:\d+\)

$input = "Text goes here (id:11223) and also here (id:33585) blah blah";
echo $input . "\n";
$output = preg_replace("/\(id:\d+\)/","",$input);
echo $output;

此打印:

Text goes here (id:11223) and also here (id:33585) blah blah
Text goes here  and also here  blah blah

这里有一个边缘情况,您可以在替换后留下的可能的(不需要的)提取空白中看到。我们也可以尝试使它复杂化并删除它,但是您应该声明期望的输出是什么。

本文链接:https://www.f2er.com/3140569.html

大家都在问