Home > Backend Development > PHP Tutorial > PHP怎么匹配img标签外的数据并替换,img的数据不变

PHP怎么匹配img标签外的数据并替换,img的数据不变

WBOY
Release: 2016-06-06 20:20:45
Original
1348 people have browsed it

我在添加文章的时候,需要自动生成锚文本,关键词去匹配文章内容时,会匹配到img的alt和title值,图片会出现异常。
各位大神,帮我解决一下!谢谢了!

原来想要的是<p><img title="xxx" alt="PHP怎么匹配img标签外的数据并替换,img的数据不变" >这些文字加链接</p>
出错内容:<img title="<a href=" http: alt="PHP怎么匹配img标签外的数据并替换,img的数据不变" >xxx'/>

我的代码是这样写的:

<code>/**
 * 多关键词替换,每个替换一次
 * @param  Mixed $search   查找目标值
 * @param  Mixed $replace  替换值
 * @param  Mixed $subject  执行替换的字符串/数组
 * @param  Int   $limit    允许替换的次数,默认为-1,不限次数
 * @return Mixed
 */
function str_replace_limit($search, $replace, $subject, $limit=-1){
    if(is_array($search)){
        foreach($search as $k=>$v){
            $search[$k] = '`'. preg_quote($search[$k], '`'). '`';
        }
    }else{
        $search = '`'. preg_quote($search, '`'). '`';
    }
    return preg_replace($search, $replace, $subject, $limit);
}
foreach ($keylink as $k){
        $keyArray[] = $k->word;
        $url = '<a href="'.%24k->url.'" style="color:red;font-size:1.2em;">'.$k->word.'</a>';
        $replacement[] = $url;
}</code>
Copy after login
Copy after login

回复内容:

我在添加文章的时候,需要自动生成锚文本,关键词去匹配文章内容时,会匹配到img的alt和title值,图片会出现异常。
各位大神,帮我解决一下!谢谢了!

原来想要的是<p><img title="xxx" alt="PHP怎么匹配img标签外的数据并替换,img的数据不变" >这些文字加链接</p>
出错内容:<img title="<a href=" http: alt="PHP怎么匹配img标签外的数据并替换,img的数据不变" >xxx'/>

我的代码是这样写的:

<code>/**
 * 多关键词替换,每个替换一次
 * @param  Mixed $search   查找目标值
 * @param  Mixed $replace  替换值
 * @param  Mixed $subject  执行替换的字符串/数组
 * @param  Int   $limit    允许替换的次数,默认为-1,不限次数
 * @return Mixed
 */
function str_replace_limit($search, $replace, $subject, $limit=-1){
    if(is_array($search)){
        foreach($search as $k=>$v){
            $search[$k] = '`'. preg_quote($search[$k], '`'). '`';
        }
    }else{
        $search = '`'. preg_quote($search, '`'). '`';
    }
    return preg_replace($search, $replace, $subject, $limit);
}
foreach ($keylink as $k){
        $keyArray[] = $k->word;
        $url = '<a href="'.%24k->url.'" style="color:red;font-size:1.2em;">'.$k->word.'</a>';
        $replacement[] = $url;
}</code>
Copy after login
Copy after login

能看下代码不

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template