简体   繁体   中英

php how to replace multi first | and last | to other character in string

Example I have: Today is | nice day | go to | school now | and enjoy | your life |. Today is | nice day | go to | school now | and enjoy | your life |.

I tried:

$text = str_replace('| ','"',$text);
$text = str_replace(' |','"',$text);

Result is:

Today is "nice day "go to "school now "and enjoy "your life ".

you can see result bad -> ...day "go ; ...now "and ; ...life ".

Result should be: Today is "nice day" go to "school now" and enjoy "your life".

I have many text like this to replace, please help!

Try this, using a regular expression to replace matches. In this case, we also capture the text between two | markers and use the captured text in the replacement:

$text = "Today is | nice day | go to | school now | and enjoy | your life |.";
echo $text; echo "\r\n\r\n";

$text = preg_replace("~\| (.*?) \|~", '"$1"', $text);
echo $text; echo "\r\n\r\n";

See this fiddle:

https://ideone.com/Zlij00

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