Jump to content

got a problem with str_replace


x-Boy

Recommended Posts

I got a problem with str_replace, if you try the code below you'll see it doesn't return the assigned pronunciation correctly, and I don't know what's going wrong.

 

I wonder if somebody can tell me what's going wrong and how I can solve it?

 


function abc_pronunciation($incoming_input)
{
    $arr_search = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');

    $arr_replace = array(' ay ',' be ',' ce ',' dee ',' ee ',' aef ',' gee ',' aich ',' ii ',' jay ',' kay ',' el ',' em ',' en ',' oh ',' pee ',' qu ',' ar ',' as ',' tee ',' yu ',' vee ',' doble-yu ',' ex ',' ye ',' zee ');
    
    $output = str_replace($arr_search,$arr_replace,$incoming_input);
    
    echo $output;
} 

$input = "barcelona";

abc_pronunciation($input);

Link to comment
https://forums.phpfreaks.com/topic/151199-got-a-problem-with-str_replace/
Share on other sites

scrap that this one works i just tried it myself

 

function abc_pro($incoming_input)
{
    $arr_search = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');

    $arr_replace = array(' ay ',' be ',' ce ',' dee ',' ee ',' aef ',' gee ',' aich ',' ii ',' jay ',' kay ',' el ',' em ',' en ',' oh ',' pee ',' qu ',' ar ',' as ',' tee ',' yu ',' vee ',' doble-yu ',' ex ',' ye ',' zee ');
   
    $output = $incoming_input;

    for($i=1;$i<=26;$i++)
    {
        $output = str_replace($arr_search[$i], $arr_replace[$i], $output);
    }

    echo $output;
}

$input = "barcelona";

echo(abc_pro($input));

Both functions don't work (for me) and shouldn't work, because when b is replaced with be, the e in be is then replaced with ce and so on. As genericnumber1 said, strtr() should be used:

 

<?php
function abc_pro ($str) {
$replace_pairs = array(
	'a' => ' ay ',
	'b' => ' be ',
	'c' => ' ce ',
	'd' => ' dee ',
	'e' => ' ee ',
	'f' => ' aef ',
	'g' => ' gee ',
	'h' => ' aich ',
	'i' => ' ii ',
	'j' => ' jay ',
	'k' => ' kay ',
	'l' => ' el ',
	'm' => ' em ',
	'n' => ' en ',
	'o' => ' oh ',
	'p' => ' pee ',
	'q' => ' qu ',
	'r' => ' ar ',
	's' => ' as ',
	't' => ' tee ',
	'u' => ' yu ',
	'v' => ' vee ',
	'w' => ' double-yu ',
	'x' => ' ex ',
	'y' => ' ye ',
	'z' => ' zee '
);
return strtr($str, $replace_pairs);
}
echo abc_pro('barcelona');
//output: be ay ar ce ee el oh en ay
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.