regex: If string contains specific word within bracket, then remove bracket and its content(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:如果字符串在方括号中包含特定单词,则删除方括号及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:regex:如果字符串在方括号中包含特定单词,则删除方括号及其内容


猜你喜欢
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01