drb56625 2017-04-07 15:01
浏览 92

PHP - 将字符串替换为正常,仅反转一次

I need to replace each word only once, and vice versa. To do taht, I used a code that does not work, and I can not find an answer to my question.

Input:

hello w1 w2 w12 new1 new12 new2

Expected output:

hello new1 new2 w12 w1 new12 w2

I need words / phrases into the text to replace.

w1 replace with new1

w12 unchanged

w2 replace with new2

new1 replace with w1

new12 unchanged

new2 replace with w2

Of course my text in Persian

My code is:

$string="hello w1 w2 w12 new1 new12 new2";

$fword= array("w1","w2");
$lword= array("new1","new2");

$cnt=0;
$string=str_replace($fword,$lword,$string,$cnt);
$string=str_replace($lword,$fword,$string,$cnt);
echo "<h2>Change in string: $cnt <br> New String: $string </h2>";

But it is wrong

I also use this code:

$string="hello w1 w2 w12 new1 new12 new2";

$fword= array("w1","w2","new1","new2");
$lword= array("new1","new2","w1","w2");

$cnt=0;
$string=str_replace($fword,$lword,$string,$cnt);
echo "<h2>Change in string: $cnt <br> New String: $string </h2>";
  • 写回答

3条回答 默认 最新

  • dongzhe3171 2017-04-07 15:13
    关注

    You can tokenize your string with strtok.

    Then check the tokens in a reverse loop, and if the truncated token is in the allowed words list, replace it (you can have a mapping array like ["W1" => "E1", ...]). If such a word was already replaced, just go further.

    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题