doujiao7520 2013-07-25 17:57
浏览 28
已采纳

str_replace仅匹配

Good Day,

I am trying to create a morse code to text and text to morse code converter.

My code:

$letter = str_split(strtolower($_POST['text']));
$morse = $_POST['morse'];
$morsecmp = explode(" ",$morse);
$letter = implode(" ",$letter);
$mode = $_POST['sub'];

$morsecode = array(".-","-...","-.-.","-..","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",
            ".--.","--.-",".-.","...","-.","..-","...-",".--","-..-","-.--","--..",".");
$letters = array("a","b","c","d","f","g","h","i","j","k","l","m","n","o","p","q","r",
            "s","t","u","v","w","x","y","z","e");

if($mode == "Text to Morse Code"){  
    $letter = str_replace($letters,$morsecode,$letter);
    $translated = $letter;
}else{
    for($x=0;$x<sizeof($letters);$x++){
        for($y=0;$y<sizeof($morsecmp);$y++){

            if($morsecode[$x] === $morsecmp[$y]){
                echo $morsecode[$x]." === ".$letters[$x]."<br>";
                $morse = str_replace($morsecode[$x],$letters[$x],$morse);
            }
        }
    }
    $translated = $morse;
}

sample input:

.... . .-.. .-.. --- .-- --- .-. .-.. -..

sample output:

h e ed ed o w o r ed d

expected output:

hello wolrd

My problem is that when converting from morse code to text some characters are not captured properly due to str_replace limit where it will replace all string that is similar to the needle, so if i have to replace all "." to e it will also change "...." which should be actually an h.

any help on this would be greatly appreciated.

Thank You.

  • 写回答

3条回答 默认 最新

  • dousu1900 2013-07-25 18:04
    关注

    Just when you repalce the characters add an extra space for the search string.

     $morse = $_POST['morse']." ";  // this is to add an extra space at the end of the morse string.
    

    Now we replace all occurrences of morse code strings followed by space with the desired letter.

     $morse = str_replace($morsecode[$x]." ",$letters[$x],$morse);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示