忽略 preg_replace 中的某些匹配项
Ignore certain matches in preg_replace
请在下面找到 php 个字符串:
$string = 'hi this is testing [ok i can remove it] and
then [ok i can remove it too] and then I want to spare [caption .... ]';
我想删除 [好吧我可以删除它] 和 [好吧我也可以删除它] 但我想使用 preg_replace 在字符串中保留 [caption .... ]。
目前我正在使用以下内容,它使用 [ ]
删除所有内容
$return = preg_replace( array('~\[.*]~'), '', $b );
请多多指教
对于这种工作,我会像这样使用 preg_replace_callback:
$string = 'hi this is testing [ok i can remove it] and then [ok i can remove it too] and then I want to spare [caption .... ]';
$return = preg_replace_callback(
'~\[[^\]]*\]~',
function($m) {
if (preg_match('/\bcaption\b/', $m[0]))
return $m[0];
else
return '';
},
$string);
echo $return,"\n";
输出:
hi this is testing and then and then I want to spare [caption .... ]
请在下面找到 php 个字符串:
$string = 'hi this is testing [ok i can remove it] and
then [ok i can remove it too] and then I want to spare [caption .... ]';
我想删除 [好吧我可以删除它] 和 [好吧我也可以删除它] 但我想使用 preg_replace 在字符串中保留 [caption .... ]。 目前我正在使用以下内容,它使用 [ ]
删除所有内容$return = preg_replace( array('~\[.*]~'), '', $b );
请多多指教
对于这种工作,我会像这样使用 preg_replace_callback:
$string = 'hi this is testing [ok i can remove it] and then [ok i can remove it too] and then I want to spare [caption .... ]';
$return = preg_replace_callback(
'~\[[^\]]*\]~',
function($m) {
if (preg_match('/\bcaption\b/', $m[0]))
return $m[0];
else
return '';
},
$string);
echo $return,"\n";
输出:
hi this is testing and then and then I want to spare [caption .... ]