我想做一个str_replace,这样它就替换了(一组针中的)第一个针,并忽略了字符串中的其余针。
这不起作用:
str_replace ( $needles, $replace , $mystring, 1 )
例如
$needles = array('#a#', '#b#');
$replace = array ('1', '2');
$mystring = "this #b# is #b# a test #a# string";
我想解析$mystring,使其输出为:
$mystring = "this 2 is a test string";
因此,它找到的第一根针遵循替换数组中指示的规则,随后的所有针都被一根空白字符串替换。
希望这是有道理的,很难用语言来解释我的想法。
我有一个非常好的解决方案(也很快),不需要循环:
$replace = array( //This will make your life really easy
"#a#" => 1,
"#b#" => 2
);
$pattern = "/(" . implode("|", array_keys($replace)) . ")/" ;
$string = "this #b# is #b# a test #a# string";
preg_match_all($pattern, $string, $matches);
$string = preg_replace("/{$matches[0][0]}/", "{$replace[$matches[0][0]]}", $string, 1);
$string = preg_replace($pattern, "", $string);
echo $string ;
你必须有循环才能获得这种效果:
$needles = array('/#b#/', '/#a#/');
$replace = array ('2', '1');
$mystring = "this #b# is #b# a test #a# string";
for ($i=0; $i<count($needles); $i++) {
$repl = preg_replace ( $needles[$i], $replace[$i], $mystring, 1 );
if ($repl != $mystring) break; // 1st replacement done
}
for ($i=0; $i<count($needles); $i++)
$repl = preg_replace ( $needles[$i], '', $repl, 1 );
var_dump($repl);
输出:
string(25) "this 2 is a test string"
$needles = array('#a#', '#b#');
$replace = array('1', '2');
$mystring = "this #b# is #b# a test #a# string";
$start = PHP_INT_MAX;
foreach ($needles as $needle)
if ((int)$start != ($start = min(strpos($mystring, $needle), $start)))
$replacement = $replace[$key = array_flip($needles)[$needle]];
$mystring = str_replace($needles, "", substr_replace($mystring, $replacement, $start, strlen($needles[$key])));
输出:
var_dump($mystring);
// =>
string(25) "this 2 is a test string"