preg_replace to exclude PHP

前端 未结 2 1381
清歌不尽
清歌不尽 2021-01-20 02:05

Im using preg_replace to replace keywords in text with a href tag, my regex is working awesome, right now my code is:

$newstring2 = preg_replace(\"/\\p{L}*?\         


        
相关标签:
2条回答
  • 2021-01-20 02:48

    If it must be done with regex I think PCRE verbs are your best option. Exclude all links then search for the term with word boundaries.

    <a[\S\s]+?<\/a>(*SKIP)(*FAIL)|\bTERM\b
    

    Demo: https://regex101.com/r/KlE1kc/1/

    an example of a flaw with this though is if the a ever had a </a> in it. e.g. onclick='write("</a>")' a parser is really the best approach. There are a lot of gotchas with HTML and regexs.

    0 讨论(0)
  • 2021-01-20 02:49

    How about this with negative lookahead. Regex

    Explanation: capture all the keyword that is called text and replace with it some link but don't capture those keywords that have </a> after it.

    $re = '/(text)(?!<\/a>)/m';
    $str = 'this is sample text about something what is text.
    
    this is sample <a href=\'somelink.php\'>text</a> about something what is <a href=\'somelink.php\'>text</a>.';
    $subst = '<a href=\'somelink.php\'>$1</a>';
    
    $result = preg_replace($re, $subst, $str);
    
    echo $result;
    

    Output:

    this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>. 
    
    this is sample <a href='somelink.php'>text</a> about something what is <a href='somelink.php'>text</a>.
    

    DEMO: https://3v4l.org/DVTB1

    0 讨论(0)
提交回复
热议问题