php只替换一次不重复【如何不替换<img>标签中的属性值,如alt,title】

现在的代码如下,如何在这个基础上添加条件,【不替换<img>标签中的属性,如alt,title】publicfunctionstr_replace_once($needl... 现在的代码如下,如何在这个基础上添加条件,【不替换<img>标签中的属性,如alt,title】
public function str_replace_once($needle,$replace,$haystack)
{
$pos = strpos($haystack, $needle);

if ($pos === false)
{
return $haystack;
}

return substr_replace($haystack, $replace, $pos, strlen($needle));
}
展开
 我来答
dispose
2016-12-01 · TA获得超过642个赞
知道小有建树答主
回答量:458
采纳率:0%
帮助的人:508万
展开全部

我试着写了一个,仅供参考:

function str_replace_once_new($needle,$replace,$haystack) {
    $pattern = '/<img[^>]*>/is';
    preg_match_all($pattern, $haystack, $matched);
    if(empty($matched[0])){
        $pos = strpos($haystack, $needle);
        if ($pos === false) {
            return $haystack;
        }
        return substr_replace($haystack, $replace, $pos, strlen($needle));
    } else {
        $arr = preg_split($pattern, $haystack);
        $haystack_new = '';
        $replace_time = 0;
        foreach($arr as $key => $str){
            $pos = strpos($str, $needle);
            if ($pos === false || $replace_time > 0) {
                $haystack_new .= $str;
            } else {
                $haystack_new .= substr_replace($str, $replace, $pos, strlen($needle));
                $replace_time  = 1;
            }
            if(isset($matched[0][$key])) $haystack_new .= $matched[0][$key];
        }
        return $haystack_new;
    }
}
更多追问追答
追问

感谢您的回答,为什么会出现这样的情况,一直在重复某个链接

因为我的替换形式是一个类似百度知道的问答平台,可能有10个回答都带有某一个需要替换的关键词,我感觉现在的代码是如果这个页面出现1次就累加一次这个链接,不知道如何优化,请指导

追答

那是因为你执行了多次这个替换函数,具体原因只有你自己找了。

如果你要做的是给关键字加链接,可以加个判断条件试一试:

function str_replace_once_new($needle,$replace,$haystack) {
    //...
            $pos = strpos($str, $needle);
            if ($pos === false || $replace_time > 0 || strpos($str, $needle.'</a>') !== false) {
                $haystack_new .= $str;
            } else {
                $haystack_new .= substr_replace($str, $replace, $pos, strlen($needle));
                $replace_time  = 1;
            }
    //...
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式