2016-03-03 57 views
0

我的代碼如下結果:preg_grep不顯示用雙引號(「)

$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

'preg_grep'需要數組作爲第二個參數,而不是字符串。也許你在尋找'preg_match'? –

回答

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