regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容

2022-03-22 00:00:00 regex php preg-replace

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

我想要针对的词是:

picture
see
lorem

因此,这里有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).';

preg_replace()可以使用哪些正则表达式:

$text = preg_replace($regex, '' , $text);

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

结果应为:

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

这里有一个ideone用于测试。


解决方案

您可以使用以下方法(感谢@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);
?>

请参阅a demo on ideone.com和on regex101.com。

相关文章