正则表达式:如果字符串包含括号内的特定单词,则删除括号及其内容

Hen*_*son 2 php regex preg-replace

使用正则表达式,我想检测字符串中括号内是否存在特定单词,如果是,则删除括号及其内容.

我想要的目标是:

picture
see
lorem
Run Code Online (Sandbox Code Playgroud)

所以,这里有3个字符串示例:

$text1 = 'Hello world (see below).';
$text2 = 'Lorem ipsum (there is a picture here) world!';
$text3 = 'Attack on titan (is lorem) great but (should not be removed).';
Run Code Online (Sandbox Code Playgroud)

我可以使用什么正则表达式preg_replace():

$text = preg_replace($regex, '' , $text);
Run Code Online (Sandbox Code Playgroud)

要删除这些括号及其内容(如果它们包含这些词语)?

结果应该是:

$text1 = 'Hello world.';
$text2 = 'Lorem ipsum world!';
$text3 = 'Attack on titan great but (should not be removed).';
Run Code Online (Sandbox Code Playgroud)

这是测试的理想选择.

Jan*_*Jan 6

您可以使用以下方法(感谢@Casimir之前指出错误!):

<?php
$regex = '~
            (\h*\(                             # capture groups, open brackets
                [^)]*?                         # match everything BUT a closing bracket lazily
                (?i:picture|see|lorem)         # up to one of the words, case insensitive
                [^)]*?                         # same construct as above
            \))                                # up to a closing bracket
            ~x';                               # verbose modifier

$text = array();
$text[] = 'Hello world (see below).';
$text[] = 'Lorem ipsum (there is a picture here) world!';
$text[] = 'Attack on titan (is lorem) great but (should not be removed).';

for ($i=0;$i<count($text);$i++)
    $text[$i] = preg_replace($regex, '', $text[$i]);

print_r($text);
?>
Run Code Online (Sandbox Code Playgroud)

a demo on ideone.com对regex101.com.

  • 谢谢你的代码1月.虽然你的正则表达式还有2个问题.**如果**开口支架前面有空的空间,则在卸下支架时移除空的空间:https://regex101.com/r/nT0wI5/2它仍应检测到之前没有空间的支架他们.希望我有意义. (2认同)