Hen*_*son 2 php regex preg-replace
使用正则表达式,我想检测字符串中括号内是否存在特定单词,如果是,则删除括号及其内容.
我想要的目标是:
picture
see
lorem
Run Code Online (Sandbox Code Playgroud)
所以,这里有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).';
Run Code Online (Sandbox Code Playgroud)
我可以使用什么正则表达式preg_replace():
$text = preg_replace($regex, '' , $text);
Run Code Online (Sandbox Code Playgroud)
要删除这些括号及其内容(如果它们包含这些词语)?
结果应该是:
$text1 = 'Hello world.';
$text2 = 'Lorem ipsum world!';
$text3 = 'Attack on titan great but (should not be removed).';
Run Code Online (Sandbox Code Playgroud)
这是测试的理想选择.
您可以使用以下方法(感谢@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);
?>
Run Code Online (Sandbox Code Playgroud)
见a demo on ideone.com和对regex101.com.
| 归档时间: |
|
| 查看次数: |
1286 次 |
| 最近记录: |