如何在包含某些字符的字符串中执行正则表达式匹配字符串?

时间:2022-05-25 06:39:40

Let's say I have the following string and want to strip out "two three" whether it is in parenthesis or not.

假设我有以下字符串,并且想要删除“两个三”,无论它是否在括号中。

one two three four
one (two three) four
one ( two three ) four
one (two three four
one two three) four
one ( two three four
one two three ) four

I want to strip these to

我想剥去这些

one four

I tried that but no luck.

我试过但没有运气。

$str = preg_replace('/(\(| )two(.*?)three( |\))\S+ */i', '', $str);

2 个解决方案

#1


2  

You can use this regex :

你可以使用这个正则表达式:

(\(? ?two three ?\)?)

demo

#2


0  

The point is to match spaces or beginning of string + parenthesis or not + spaces + 'the string to strip' + spaces + parenthesis or not + spaces or end of string.

要点是匹配空格或字符串+括号的开头或不匹配+空格+'要剥离的字符串'+空格+括号或不要+空格或字符串结尾。

$str = preg_replace('/(^|\s+)\(?\s*the string to strip\s*\)?(\s+|$)/i', ' ', $str);

This may result in a space at the begining or the end, but you can trim it later. I think it is the simplest solution.

这可能会在开始或结束时产生空间,但您可以稍后修剪它。我认为这是最简单的解决方案。

#1


2  

You can use this regex :

你可以使用这个正则表达式:

(\(? ?two three ?\)?)

demo

#2


0  

The point is to match spaces or beginning of string + parenthesis or not + spaces + 'the string to strip' + spaces + parenthesis or not + spaces or end of string.

要点是匹配空格或字符串+括号的开头或不匹配+空格+'要剥离的字符串'+空格+括号或不要+空格或字符串结尾。

$str = preg_replace('/(^|\s+)\(?\s*the string to strip\s*\)?(\s+|$)/i', ' ', $str);

This may result in a space at the begining or the end, but you can trim it later. I think it is the simplest solution.

这可能会在开始或结束时产生空间,但您可以稍后修剪它。我认为这是最简单的解决方案。