...

View Full Version : String Replace/Switch Question



theflyingminstr
01-18-2010, 04:46 PM
Hi, I want to switch two numbers, but when I try to do it within an array a little bit too much switching is happening and I'm not yielding the end result I'm looking for.



<?php

$rawstring = "Replace 1 with 3, and 3 with 1.";

$placeholders = array('1', '3');

$replvals = array('3', '1');

$newstr = str_replace($placeholders, $replvals, $rawstring);

echo $newstr;

?>


Thanks so much.

JAY6390
01-18-2010, 05:07 PM
<?php

$rawstring = "Replace 1 with 3, and 3 with 1.";
$newstr = preg_replace('/\b(1|3)\b/', '[$1]', $rawstring);
$placeholders = array('[1]', '[3]');
$replvals = array('3', '1');
$newstr = str_replace($placeholders, $replvals, $newstr);
echo $newstr;

theflyingminstr
01-18-2010, 05:09 PM
Amazing, thanks so much!

JAY6390
01-18-2010, 05:16 PM
no problem

kbluhm
01-18-2010, 05:21 PM
function str_swap( $string, Array $replacements = array() )
{
if ( ! empty( $replacements ) )
{
$search = array_keys( $replacements );
$replace = array_values( $replacements );
foreach ( $search as $i => $value )
{
$string = str_replace( $value, '[[' . $i . ']]', $string );
}
foreach ( $replace as $i => $value )
{
$string = str_replace( '[[' . $i . ']]', $value, $string );
}
}
return $string;
}

// echoes: Replace 3 with 1, and 1 with 3.
echo str_swap( 'Replace 1 with 3, and 3 with 1.', array( 1 => 3, 3 => 1 ) );


You can exchange the brackets for something more unique to ensure the changes are made properly. If [[0]], etc, already exists in the original string (rare but possible) it would throw the whole thing off.

JAY6390
01-18-2010, 05:28 PM
I did consider the possibility of that, but the example looked so simple I didn't think it would matter :)

MattF
01-18-2010, 05:48 PM
Nothing like a good bit of overkill chaps. :D



$string = "Replace 1 with 3, and 3 with 1.";
$string = str_replace(array('1', '3'), array('3', '1'), $string);

print($string);

JAY6390
01-18-2010, 05:50 PM
That produces
Replace 1 with 1, and 1 with 1. which is why the examples above had the tags

MattF
01-18-2010, 06:03 PM
Oops. :D Duly chastised.

theflyingminstr
01-18-2010, 06:14 PM
I like the logic of the function a lot. Thanks kbluhm.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum