我想要str_replace()的一个版本,它只替换$subject中第一次出现的$search。有一个简单的解决方案,还是我需要一个hack的解决方案?
当前回答
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;
其他回答
可以用preg_replace完成:
function str_replace_first($search, $replace, $subject)
{
$search = '/'.preg_quote($search, '/').'/';
return preg_replace($search, $replace, $subject, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
神奇之处在于可选的第四个参数[Limit]。从文档中可以看到:
[极限]-最大可能 每个中的每个模式的替换 主题字符串。默认为-1 (no 限制)。
不过,请参阅zombat的回答以获得更有效的方法(大约快3-4倍)。
=> CODE已被修订,所以考虑一些太旧的注释
感谢大家帮助我改进这一点 有任何BUG,请与我沟通;我马上就去做
那么,让我们开始:
将第一个o替换为ea,例如:
$s='I love you';
$s=str_replace_first('o','ea',$s);
echo $s;
//output: I leave you
功能:
function str_replace_first($this,$that,$s)
{
$w=strpos($s,$this);
if($w===false)return $s;
return substr($s,0,$w).$that.substr($s,$w+strlen($this));
}
不幸的是,我不知道任何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));
}
我会用孕妇代替。它有一个LIMIT参数,你可以将它设置为1
preg_replace (regex, subst, string, limit) // default is -1
对于字符串
$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