regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容 [英] regex: If string contains specific word within bracket, then remove bracket and its content

查看:21
本文介绍了regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想要针对的词是:

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.comon regex101.com

这篇关于regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆