Page 1 of 1

str_replace using one array

Posted: Sat Oct 04, 2008 10:31 am
by raysleith
is there anyway to use str_replace using one array like this?

Code: Select all

 
$myarray = array( "1" => "one", "2" => "two");
 
$string = "1 2";
echo str_replace($key, $value, $string);
 
$key should be the key of $myarray
$value should be the value of $myarray

is there anyway to do this? because it's trouble some using seperate array for this case

Re: str_replace using one array

Posted: Sat Oct 04, 2008 3:24 pm
by Ziq
Actually, you can use many ways. For example:

Code: Select all

<?
//...
foreach ($myarray  as $key => $value)
{
    $string = str_replace($key, $value, $string);
}
//...
?>
or

Code: Select all

<?
//...
echo str_replace(array_keys($myarray), array_values($myarray), $string);
//...
?>

Re: str_replace using one array

Posted: Sat Oct 04, 2008 7:55 pm
by raysleith
thx for the help :D