我想做一个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";
因此,它找到的第一个针头遵循替换阵列中指示的规则,并且所有后续针头都用空白字符串替换。
希望这是有道理的,很难用言语解释我的想法。
答案 0 :(得分:2)
我有一个非常好的解决方案(也很快),不需要循环:
$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 ;
答案 1 :(得分:0)
你必须有循环才能产生这种效果:
$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"
答案 2 :(得分:0)
$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"