最近遇到一个项目中需要实现一个php字符串替换的功能,类似str_replace,但php str_replace是替换所有的匹配,想实现只替换第一次,该如何操作呢,看了一会php的官方手册,写了一下几个能用的函数,完美解决
第一种方法:使用preg_replace
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
第二种方法:substr_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;
}
第三种方法:strpos
function str_replace_limit($search, $replace, $string, $limit = 1) {
$pos = strpos($string, $search);
if ($pos === false) {
return $string;
}
$searchLen = strlen($search);
for ($i = 0; $i < $limit; $i++) {
$string = substr_replace($string, $replace, $pos, $searchLen);
$pos = strpos($string, $search);
if ($pos === false) {
break;
}
}
return $string;
}
用法示例:
$search = 'foo';
$replace = 'bar';
$string = 'foo wizard makes foo brew for evil foo and jack';
$limit = 2;
$replaced = str_replace_limit($search, $replace, $string, $limit);
echo $replaced;
// bar wizard makes bar brew for evil foo and jack
第四种方法:implode
function str_replace_first($search, $replace, $subject) {
return implode($replace, explode($search, $subject, 2));
}
未经允许不得转载:OZ分享-吉家大宝官方博客 » php7 str_replace实现只替换第一次的几种解决方案