我的代码如下:
$escapedOperator = ":";
$operator['symbol'] = ":";
$string = 'title: "space before" and text breaks';
if(count(preg_grep('/\w["]*\s*'.$escapedOperator.'\s*["]*\w/',$string))){
$search = "/\s*".$escapedOperator."\s*/";
$string = preg_replace($search,$operator['symbol'],$string);
}else{
$string=str_replace($operator['symbol'],"",$string);
}
我得到了输出:
title "space before" and text breaks
但我需要:
title:"space before" and text breaks
答案 0 :(得分:0)
如上所述,preg_grep()
需要一个数组作为第二个参数,而不是字符串。如果你改变了:
$string = 'title: "space before" and text breaks';
要:
$string = array('title: "space before" and text breaks');
您的代码有效,echo $string[0];
将输出title:"space before" and text breaks
如果目标是删除冒号(:)周围的空格,那么你能不能这样做吗?
$string = 'title: "space before" and text breaks';
$string = preg_replace('/\s*:\s*/', ":", $string);
echo $string[0];
这也会输出title:"space before" and text breaks