Hi all i need a particulary type of string replace in php. I need to replace a word with two different others words.
For example: in the string "Hi mom, hi dad" i need to automatically replace the word "hi" with two other different, for example "mary" and "john". So if there is only one occurrence of "Hi" it replace onl开发者_C百科y with "mary" but if there are more than one it uses all the association of words.
So, one word more replaces based on how many times the word occurrence. Thanks to all who can help me!
preg_replace_callback
lets you control each replacement.
You could accomplish this with multiple calls to preg_replace
, specifying a limit of 1 for each call:
$string = "Hi mom, hi dad";
preg_replace('/hi/i', 'mary', $str, 1); // "mary mom, hi dad"
preg_replace('/hi/i', 'john', $str, 1); // "mary mom, john dad"
You could generalize this with something like the following. It takes a subject, a pattern, and 1 or more replacement words.
function replace_each($subject, $pattern, $replacement) {
$count = 0;
for ($i = 2; $i < func_num_args(); ++$i) {
$replacement = func_get_arg($i);
$subject = preg_replace($pattern, $replacement, $subject, 1, $count);
if (!$count)
// no more matches
break;
}
return $subject;
}
$string = preg_replace_each("Hi mom, hi dad", "/hi/i", "mary", "john");
echo $string; // "mary mom, john dad"
preg_replace_callback is one way, another is to utilize $limit and $count parameters of preg_replace (see manpage )
$str = "hi foo hi bar hi baz hi quux";
$repl = array('uno', 'dos', 'tres');
do{
$str = preg_replace('~hi~', $repl[0], $str, 1, $count);
$repl[] = array_shift($repl); // rotate the array
} while($count > 0);
I'm not sure if there is a really easy way to do it but take a look at this piece of code i just wrote. This should do the trick for you :)
<?php
class myReplace{
public $replacements = array();
protected $counter = 0;
public function __construct($replacements) {
// fill the array with replacements
$this->replacements = $replacements;
}
public function test($matches) {
// if you want you could do something funky to the matches array here
// if the key does not exists we are gonna start from the first
// array element again.
if(!array_key_exists($this->counter, $this->replacements)) {
$this->counter = 0;
}
// this will return your replacement.
return $this->replacements[$this->counter++];
}
}
// Instantiate your class here, and insert all your replacements in sequence
$obj = new myReplace(array('a', 'b'));
// Lets start the replacement :)
echo preg_replace_callback(
"/hi/i",
array($obj, 'test'),
"Hi mom, hi dad, hi son, hi someone"
);
?>
This code will result in: a mom, b dad, a son, b someone
精彩评论