我想要str_replace()的一个版本,它只替换$subject中第一次出现的$search。有一个简单的解决方案,还是我需要一个hack的解决方案?
当前回答
对于字符串
$string = 'OOO.OOO.OOO.S';
$search = 'OOO';
$replace = 'B';
//replace ONLY FIRST occurance of "OOO" with "B"
$string = substr_replace($string,$replace,0,strlen($search));
//$string => B.OOO.OOO.S
//replace ONLY LAST occurance of "OOOO" with "B"
$string = substr_replace($string,$replace,strrpos($string,$search),strlen($search))
//$string => OOO.OOO.B.S
//replace ONLY LAST occurance of "OOOO" with "B"
$string = strrev(implode(strrev($replace),explode(strrev($search),strrev($string),2)))
//$string => OOO.OOO.B.S
对于单个字符
$string[strpos($string,$search)] = $replace;
//EXAMPLE
$string = 'O.O.O.O.S';
$search = 'O';
$replace = 'B';
//replace ONLY FIRST occurance of "O" with "B"
$string[strpos($string,$search)] = $replace;
//$string => B.O.O.O.S
//replace ONLY LAST occurance of "O" with "B"
$string[strrpos($string,$search)] = $replace;
// $string => B.O.O.B.S
其他回答
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;
For循环解决方案
<?php
echo replaceFirstMatchedChar("&", "?", "/property/details&id=202&test=123#tab-6");
function replaceFirstMatchedChar($searchChar, $replaceChar, $str)
{
for ($i = 0; $i < strlen($str); $i++) {
if ($str[$i] == $searchChar) {
$str[$i] = $replaceChar;
break;
}
}
return $str;
}
不幸的是,我不知道任何PHP函数可以做到这一点。 你可以像这样很容易地自己卷:
function replace_first($find, $replace, $subject) {
// stolen from the comments at PHP.net/str_replace
// Splits $subject into an array of 2 items by $find,
// and then joins the array with $replace
return implode($replace, explode($find, $subject, 2));
}
补充一下人们所说的,记住整个字符串是一个数组:
$string = "Lorem ipsum lá lá lá";
$string[0] = "B";
echo $string;
“Borem ipsum there there”
编辑:两个答案都已更新,现在是正确的。我将把答案留下,因为函数时间仍然是有用的。
“僵尸”和“太多php”的答案很不幸是不正确的。这是对僵尸发布的答案的修正(因为我没有足够的声誉来发表评论):
$pos = strpos($haystack,$needle);
if ($pos !== false) {
$newstring = substr_replace($haystack,$replace,$pos,strlen($needle));
}
注意strlen($needle),而不是strlen($replace)。Zombat的例子只有在针头和替代物长度相同的情况下才能正确工作。
下面是与PHP自己的str_replace具有相同签名的函数中的相同函数:
function str_replace_first($search, $replace, $subject) {
$pos = strpos($subject, $search);
if ($pos !== false) {
return substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
这是修改后的“too much php”的答案:
implode($replace, explode($search, $subject, 2));
注意最后的2而不是1。或函数格式:
function str_replace_first($search, $replace, $subject) {
return implode($replace, explode($search, $subject, 2));
}
我对这两个函数进行了计时,当没有找到匹配时,第一个函数的速度是原来的两倍。当找到匹配时,它们的速度是一样的。