用 php 替换字符串中的 2 个单词
replace 2 words in a string with php
如何在 php 中进行替换,我的第一个标题是这样的:
the price From example To example is 3,
我也想输出相同的标题,但要这样更改:
the price To example From example is 3,
我使用下面的代码,但没有更改第二个单词。我明白了:
the price To example To example is 3,
echo str_replace(array("From","To"), array("To","From"), $title);
试试这个。
$phrase = "the price From example To example is 3";
$texta = array("From", "To");
$textb = array("To", "From");
$newphrase = str_replace($texta, $textb, $phrase);
你想要strtr:
$newTitle = strtr($title, array("From"=>"To", "To"=>"From"));
所以问题是 str_replace 将按照您的数组顺序执行替换,无论您将它们放入的顺序如何,它总是会覆盖第一个替换。
第一步是告诉 str_replace 查找“From”并替换为“To”。在这一点上做你的短语:
the price From example To example is 3
变成
the price To example To example is 3
然后 str_replaces 到数组中的下一项,即查找 "To" 并将其替换为 "From"。此时您可能会看到问题所在。
使用 ChrisMoll 的回答。
如何在 php 中进行替换,我的第一个标题是这样的:
the price From example To example is 3,
我也想输出相同的标题,但要这样更改:
the price To example From example is 3,
我使用下面的代码,但没有更改第二个单词。我明白了:
the price To example To example is 3,
echo str_replace(array("From","To"), array("To","From"), $title);
试试这个。
$phrase = "the price From example To example is 3";
$texta = array("From", "To");
$textb = array("To", "From");
$newphrase = str_replace($texta, $textb, $phrase);
你想要strtr:
$newTitle = strtr($title, array("From"=>"To", "To"=>"From"));
所以问题是 str_replace 将按照您的数组顺序执行替换,无论您将它们放入的顺序如何,它总是会覆盖第一个替换。
第一步是告诉 str_replace 查找“From”并替换为“To”。在这一点上做你的短语:
the price From example To example is 3
变成
the price To example To example is 3
然后 str_replaces 到数组中的下一项,即查找 "To" 并将其替换为 "From"。此时您可能会看到问题所在。
使用 ChrisMoll 的回答。