search

Home  >  Q&A  >  body text

Regular expression - PHP regular expression determines whether there are specified keywords in a and img tags

What I want to implement is the keyword replacement function. a. img contains keywords and cannot be replaced.
If [Example] is a keyword, the keyword appears in these three situations and cannot be replaced, otherwise it will destroy the html structure

<a href="#" title="这是一个例子而已">这是一个例子而已</a>
<img src="#" alt="我是例子呀">

<a href="#" title="这是一个例子">这是一个例子</a>
<img src="#" alt="我是例子">

<a href="#" title="例子而已">例子而已</a>
<img src="#" alt="例子呀">

被破坏的<img src="#" alt="破坏了<a href="#">例子</a>破坏的可能性有多大?"/>

<?php
    function findword($word,$html){
        $str_reg = '(<a[^>]+>)(.*)('.$word.')(.*)(<\/a[^>]*>)';
        $str_reg .= '|(<img)(.*?)('.$word.')(.*?)(>)' ;
        if(preg_match("/$str_reg/",$html)){
            return true;
        }else{
            return false;
        }
    }
?>

Write a crappy function. It doesn't seem right.

欧阳克欧阳克2714 days ago1239

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-06-21 10:12:32

    You first replace the ones that break the rules, such as htmlspecialchars processing, and then replace them again

    reply
    0
  • Cancelreply