简体   繁体   中英

preg_grep does not show result with double quotes(")

My code is as follows:

 $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);                 
 }

I am getting output:

title "space before" and text breaks 

But I need:

title:"space before" and text breaks 

As mentioned above, preg_grep() requires an array as a second parameter, rather than a string. If you change your:

$string = 'title: "space before" and text breaks';

To:

$string = array('title: "space before" and text breaks');

Your code works, and echo $string[0]; , will output title:"space before" and text breaks

If the objective is to just remove whitespace around the colon (:), then could you not just do this?

$string = 'title: "space before" and text breaks';
$string = preg_replace('/\s*:\s*/', ":", $string);
echo $string[0];

This will also output title:"space before" and text breaks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM