Home > Back-end >  php how to replace multi first | and last | to other character in string
php how to replace multi first | and last | to other character in string

Time:11-01

Example I have: 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!

CodePudding user response:

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

  • Related