Can Regex / preg_replace be used to add an anchor tag to a keyword?

I would like to be able to switch this ...

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this keyword here.

For...

My sample [a id="keyword" href="someURLkeyword"] test keyword test[/a] link this [a href="url"]keyword[/a] here.

I can't just replace all instances of "keyword" because some of them are used in or within an existing anchor tag.

Note. Using PHP5 preg_replace on Linux.

+1


source to share


2 answers


Using regular expressions might not be the best way to fix this problem, but here's a quick fix:

function link_keywords($str, $keyword, $url) {
    $keyword = preg_quote($keyword, '/');
    $url = htmlspecialchars($url);

    // Use split the string on all <a> tags, keeping the matched delimiters:
    $split_str = preg_split('#(<a\s.*?</a>)#i', $str, -1, PREG_SPLIT_DELIM_CAPTURE);

    // loop through the results and process the sections between <a> tags
    $result = '';
    foreach ($split_str as $sub_str) {
        if (preg_match('#^<a\s.*?</a>$#i', $sub_str)) {
            $result .= $sub_str;
        } else {
            // split on all remaining tags
            $split_sub_str = preg_split('/(<.+?>)/', $sub_str, -1, PREG_SPLIT_DELIM_CAPTURE);
            foreach ($split_sub_str as $sub_sub_str) {
                if (preg_match('/^<.+>$/', $sub_sub_str)) {
                    $result .= $sub_sub_str;
                } else {
                    $result .= preg_replace('/'.$keyword.'/', '<a href="'.$url.'">$0</a>', $sub_sub_str);
                }
            }
        }
    }
    return $result;
}

      



The general idea is to split the string into links and everything else. Then strip everything behind the tag links into tags and text and paste the links in plain text. This will prevent the [p class = "] keyword from expanding to [p class =" [a href = "url"] keyword [/ a] "].

Again, I would try to find a simpler solution that doesn't include regexes.

+2


source


You cannot do this with regular expressions. Regular expressions are context free - they just match the pattern, regardless of the environment. To do what you want, you need to parse the source in an abstract view and then convert it to the target output.



+2


source







All Articles