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

时间:2016-03-13 14:52:16

标签: php regex 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用于测试。

2 个答案:

答案 0 :(得分: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);
?>

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

答案 1 :(得分:3)

您可以使用此正则表达式进行搜索:

\h*\([^)]*\b(?:picture|see|lorem)\b[^)]*\)

这意味着

\h*                    # match 0 or more horizontal spaces
\(                     # match left (
[^)]*                  # match 0 or more of any char that is not )
\b                     # match a word boundary
(?:picture|see|lorem)  # match any of the 3 keywords
\b                     # match a word boundary
[^)]*                  # match 0 or more of any char that is not )
\)                     # match right )

并替换为空字符串:

RegEx Demo

<强>代码:

$re = '/\h*\([^)]*\b(?:picture|see|lorem)\b[^)]*\)/'; 

$result = preg_replace($re, '', $input);
相关问题