gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:32:10 26 4
gpt4 key购买 nike

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

我想要定位的词是:

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 .

关于php - 正则表达式:如果字符串包含括号内的特定单词,则删除括号及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35971710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com