简体   繁体   English

php 如何先替换multi | 最后 | 到字符串中的其他字符

[英]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 |. 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 ;你可以看到结果不好 -> ...day "go ; ...now "and ; ...life ".

Result should be: 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 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 https://ideone.com/Zlij00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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