php - str_replace exact match only -


good day,

i trying create morse code text , text 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 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 when converting morse code text characters not captured due str_replace limit replace string similar needle, if have replace "." e change "...." should h.

any on appreciated.

thank you.

just when repalce characters add space search string.

 $morse = $_post['morse']." ";  // add space @ end of morse string. 

now replace occurrences of morse code strings followed space desired letter.

 $morse = str_replace($morsecode[$x]." ",$letters[$x],$morse); 

Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -