str_replace using one array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
raysleith
Forum Newbie
Posts: 10
Joined: Sat Oct 04, 2008 10:26 am

str_replace using one array

Post 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
User avatar
Ziq
Forum Contributor
Posts: 194
Joined: Mon Aug 25, 2008 12:43 am
Location: Russia, Voronezh

Re: str_replace using one array

Post 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);
//...
?>
raysleith
Forum Newbie
Posts: 10
Joined: Sat Oct 04, 2008 10:26 am

Re: str_replace using one array

Post by raysleith »

thx for the help :D
Post Reply