php替换一次

WBOY
WBOYOriginal
2016-06-23 14:31:49975browse

最近在写一个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;
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php引用传值(转)Next article:PHP你知道的