首页 > 解决方案 > 括号中特定 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()功能从数据馈送中删除这些。不要问我为什么他们决定在描述字符串中包含一个 ID……这也让我大吃一惊,为什么它不是 JSON 提要中的一个单独的列。

标签: phpregexstringpattern-matching

解决方案


尝试使用模式\(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

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


推荐阅读