Ignore css inside a string in a regex/preg_replace function

I've written this code to link all hashtags in my blog posts:

function HashTags($string){
    global $post_userid;
    return preg_replace(
        '/\s*#([a-zA-Z0-9\-_]+)/i',
        " <a href=\"blog.php?id=".$post_userid."&search=$1\">#$1</a>",
        $string
    );
}

And it works awesome! but the problem is, that if there is some CSS code inside the same string, this function transform that css too..

Ex:

<div style="color: #fff">Hello world</div>

My question is: Is it possible to ignore that css with my regex function to avoid turning that #fff into a link too...

Upvotes: 1

Views: 106

Answers (1)

JalalJaberi
JalalJaberi

Reputation: 2617

I have an idea,

  1. Remove all tags with strip_tags
  2. Search and find all hash-tagged keywords in resulted text
  3. Store found keywords in a list temporary
  4. Use a function to replace all keywords as you wish

Something like that:

function HashTags($string){
    global $post_userid;
    $tmp = strip_tags($string);
    preg_match_all('/\s*#[a-zA-Z0-9\-_]+/i', $tmp, $matches);
    foreach ($matches as $match) {
        $string = str_replace(
            $match,
            " <a href=\"blog.php?id=".$post_userid."&search=" . substr($match[0],1) . "\">$match[0]</a>",
            $string
        );
    }
    return $string;
}

It's not so clean but you can make it clean.

Upvotes: 1

Related Questions