I have the string $var in which I need to replace some text. The first \"X\" needs to be replaced by \"A\", the second \"X\" needs to be replaced by B and so on, here is an exam
You could use preg_replace_callback():
// as many as you think you'll need, maximum.
// this can be programmatically generated, if need be
$replacements = array('A', 'B', 'C', 'D', 'E', 'F', 'G'); // and so on
function get_replace_value($matches) {
global $replacements;
return array_shift($replacements);
}
$var = preg_replace_callback("/" + preg_quote($needle) + "/",
"get_replace_value", $var);
You could use preg_replace's limit
argument to only replace once.
<?php
$var = 'X X X X';
$replace = array('A', 'B', 'C', 'D');
foreach($replace as $r)
$var = preg_replace('/X/', $r, $var, 1);
echo $var;
?>
http://codepad.viper-7.com/ra9ulA
$var = 'X X X X';
$replacements = array('A', 'B', 'C', 'D');
$var = preg_replace_callback('/X/', function() use (&$replacements) {
return array_shift($replacements);
}, $var);
Other solution:
$var = preg_replace('/X/', 'A', $var, 1);
$var = preg_replace('/X/', 'B', $var, 1);
$var = preg_replace('/X/', 'C', $var, 1);
$var = preg_replace('/X/', 'D', $var, 1);
This one uses the $limit
parameter of preg_replace (we replace only one occurrence per call).
Lots of loops are happening in the other answers, here's an alternative.
$var = 'X X X X X X X';
$replace = array('A', 'B', 'C', 'D');
$var = preg_replace(array_fill(0, count($replace), '/X/'), $replace, $var, 1);
echo $var; // A B C D X X X
Without use of regex
$arr = explode('X', 'X X X X');
$rep = array('A','B','C','D');
foreach ($arr as $idx=>$val)
{
$arr[$idx] = $val.$rep[$idx];
}
echo implode($arr);
Yet one more solution (more for a dynamic number of Xs):
<?php
$foo = 'X X X X X X';
$Xs = preg_match_all('/\bX\b/',$foo,$_); if ($Xs === false) $Xs = 0;
$alphabet = range('A', chr(64 + $Xs));
foreach ($alphabet as $letter){
$foo = preg_replace('/\bX\b/', $letter, $foo, 1);
}
echo $foo;
I also added the \b
in to the pattern to only replace Xs that are free-standing, so "FAUX PAS X" only replaces the last X.
demo
alphabet_replace (more modular form)