regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容
本教程将介绍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.com和on regex101.com。
好了关于regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。