我从PHP开始,我尝试删除所有出现的字符串。我的字符串是这样的。
'This is [a test] try [it]'
我想要做的是删除所有出现的[]和方括号内的文字。
我希望结果如下:
'This is try'
我如何实现这一目标?
答案 0 :(得分:3)
您可以使用preg_replace功能。
preg_replace('~\[[^\]]*\]~', '', $string);
[^\]]*
否定字符类,它匹配任何字符,但不匹配右括号]
,零次或多次。
添加额外的修剪函数以从结果字符串中删除前导或尾随空格。
$string = 'This is [a test] try [it]';
$result = preg_replace('~\[[^\]]*\]~', '', $string);
echo trim($result, " ");
答案 1 :(得分:0)
你可以试试这个:
$myString = 'This is [a test] try [it]';
$myString = preg_replace('/\[[\w ]+\] */', '', $myString);
var_dump($myString);
说明:
/\[[\w ]+\]/g
\[ matches the character [ literally
[\w ]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\w match any word character [a-zA-Z0-9_]
' ' the literal character ' '
\] matches the character ] literally