删除 php 中出现的字符串
Remove occurrence of string in php
我从 PHP 开始,我尝试删除所有出现的字符串。我的字符串是这样的。
'This is [a test] try [it]'
我想做的是删除所有出现的 [] 和方括号内的文本。
我希望结果类似于:
'This is try'
.
我怎样才能做到这一点?
您可以使用 preg_replace 函数。
preg_replace('~\[[^\]]*\]~', '', $string);
[^\]]*
否定字符 class 匹配任何字符但不匹配右括号 ]
,零次或多次。
添加额外的 trim 函数以从结果字符串中删除前导或尾随空格。
$string = 'This is [a test] try [it]';
$result = preg_replace('~\[[^\]]*\]~', '', $string);
echo trim($result, " ");
你可以试试这个:
$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
我从 PHP 开始,我尝试删除所有出现的字符串。我的字符串是这样的。
'This is [a test] try [it]'
我想做的是删除所有出现的 [] 和方括号内的文本。
我希望结果类似于:
'This is try'
.
我怎样才能做到这一点?
您可以使用 preg_replace 函数。
preg_replace('~\[[^\]]*\]~', '', $string);
[^\]]*
否定字符 class 匹配任何字符但不匹配右括号 ]
,零次或多次。
添加额外的 trim 函数以从结果字符串中删除前导或尾随空格。
$string = 'This is [a test] try [it]';
$result = preg_replace('~\[[^\]]*\]~', '', $string);
echo trim($result, " ");
你可以试试这个:
$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