• Hi there,

    I’m pretty certain this is an issue relating to wordpress itself. I’m building a very basic plugin to automatically add google analytic’s event tracking code to links within posts that exist in a competitions category.

    The regular expression seems to match fine and dandy, but for some reason that I can’t work out, it seems to ignore the first instance (or if I’ve repeated the link to test, it will ignore the first few instances – I’ve got the link repeated 5 times in the top of the post, the first 4 don’t match, the 5th does – similarly, the same link repeated 5 times in the bottom of the post matches every time)

    Pretty sure this isn’t an issue with the regular expression I’m using but I’m a newb to regex so I’ll entertain the idea that I could be at fault ??

    Here’s the code in the plugin:

    $content = preg_replace('/<a href="http:\/\/(.+)" title="(.+)">/i','<a href="$1" target="_blank" title="$2" onClick="_gaq.push([\'_trackEvent\', \'Competitions\', \'Click\', \'Post-ID-'.$competition.'\', \'$2\']);">', $content);

    $competition is just a reference to the Post ID to help narrow down results in GA later on.

    It takes anchor text and slaps on the google analytics event tracking. Or should do.

    Any ideas what could be causing this to skip over some of the links and not others?

Viewing 1 replies (of 1 total)
  • Thread Starter sixeleven

    (@sixeleven)

    All sorted, I think my regex was a bit crap.. re-written with a bit more of a restrictive code but seems to be doing the job now:

    #<a href="([a-zA-Z0-9:/.]+)" title="([a-zA-Z0-9\s]+)">([a-zA-Z0-9\s£]*)</a>#i

Viewing 1 replies (of 1 total)
  • The topic ‘preg_replace not matching first instance, despite exact formatting’ is closed to new replies.