【问题标题】:php how to replace multi first | and last | to other character in stringphp如何替换multi先|最后 |到字符串中的其他字符
【发布时间】:2021-12-15 22:01:29
【问题描述】:

例如我有:Today is | nice day | go to | school now | and enjoy | your life |.

我试过了:

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

结果是:

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

你可以看到结果不好 -> ...day "go ; ...now "and ; ...life ".

结果应该是:Today is "nice day" go to "school now" and enjoy "your life".

我有很多这样的文字要替换,请帮忙!

【问题讨论】:

  • 不明白school | now | and怎么变成"school now" and
  • 对不起,我打字不好,这是 |现在上学|兄弟

标签: php replace


【解决方案1】:

试试这个,使用正则表达式替换匹配项。在这种情况下,我们还捕获了两个 | 之间的文本。标记并在替换中使用捕获的文本:

$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";

看这个小提琴:

https://ideone.com/Zlij00

【讨论】:

  • 对不起,我打字不好,这是 |现在上学|兄弟,结果应该是“现在上学”
  • 是的,所以解决方案有效,对吗?
  • 看这个小提琴:ideone.com/Zlij00
  • 太好了,很高兴听到。 :) 如果您不熟悉正则表达式,您应该研究一下它们。它们在文本操作和模式匹配方面非常有用。
猜你喜欢
  • 1970-01-01
  • 2014-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2019-11-21
  • 1970-01-01
相关资源
最近更新 更多