简体   繁体   English

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

[英]Regular Expression for a specific ID in a bracket

I have little confidence when it comes to regular expressions.我对正则表达式没有信心。 Writing this in PHP code.在 PHP 代码中编写此代码。

I need to be able to filter out strings that follow this format, where the numbers can be 4~6 digits (numeric only):我需要能够过滤掉遵循这种格式的字符串,其中数字可以是 4~6 位(仅限数字):

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

I could simply remove the last word by finding the last position of a space via strrpos();我可以通过strrpos(); (it appears none of them have a trailing space from JSON feed), then use substr(); (似乎它们都没有来自 JSON 提要的尾随空格),然后使用substr(); to cut it.剪它。 But I think the more elegant way would be a substring.但我认为更优雅的方式是 substring。 The intended output would be:预期的 output 将是:

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

So this regex should match with the brackets, and the id: portion, and any contiguous numbers, such as:所以这个正则表达式应该与方括号、id: 部分和任何连续的数字匹配,例如:

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

Intending to use the preg_replace() function to remove these from a data feed.打算使用preg_replace() function 从数据馈送中删除这些。 Don't ask me why they decided to include an ID in the description string... It blows my mind too why it's not a separate column in the JSON feed altogether.不要问我为什么他们决定在描述字符串中包含一个 ID……这也让我大吃一惊,为什么它不是 JSON 提要中的单独列。

Try using the pattern \(id:\d+\) :尝试使用模式\(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;

This prints:这打印:

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

There is an edge case here, which you can see in the possible (unwanted) extract whitespace left behind after the replacement.这里有一个边缘情况,您可以在替换后留下的可能(不需要的)提取空白中看到它。 We could try to get sophisticated and remove that too, but you should state what you expected output is.我们也可以尝试变得复杂并删除它,但是您应该 state 就像您期望的 output 一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM