欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php替换一次

程序员文章站 2022-05-23 15:01:49
...
最近在写一个cms系统,用的是php,写模板的时候,需要字串只替换一次的函数,上网查了一下,有一个用递归做的,晦涩难懂,于是自己写了一个

function replace_once($replace,$str,$targetstr)/$replace为要替换的字串,$targetstr为替换字串,$str为原字串
{
$tempstr = $str;
for (;;)
{
$tempindex = strrpos($tempstr,$replace);
if($tempindex!=false)
{
$tempstr = substr($str,0,$tempindex);
}
else break;
}
$replaceindex = strlen($tempstr);
//echo$replaceindex;
//echo $replaceindex."hao";
$str = substr($str,0,$replaceindex).$targetstr.substr($str,$replaceindex+strlen($replace));
return $str;
}

相关标签: php替换一次