preg_grep不显示带双引号的结果(")

时间:2016-03-03 16:24:53

标签: php regex double-quotes

我的代码如下:

 $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 

1 个答案:

答案 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