• Hi, I’m working on a plugin which searches the content of a post for a href links and adds a style to it based on if it’s an external link or if it’s an image file.

    I’ve got the following already:

    return preg_replace(
    array(
    '/(?(?=<a>]*>.+</a>)
    (?:</a><a>]*>.+</a>)
    |
    ([^="']?)((?:https?|ftp|bf2|)://[^<> nr]+)
    )/iex',
    '/</a><a>]*)target="?[^"']+"?/i',
    '/</a><a>]+)>/i',
    '/(^|s)(www.[^<> nr]+)/iex',
    '/(([_A-Za-z0-9-]+)(.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)
    (.[A-Za-z0-9-]+)*)/iex'
    ),
    array(
    "stripslashes((strlen('2')>0?'1</a><a>2</a>3':''))",
    '<a1',
    '<a rel="lightbox">',
    "stripslashes((strlen('2')>0?'1</a><a>2</a>3':''))",
    "stripslashes((strlen('2')>0?'<a></a>':''))"
    ),
    $text
    );

    I have two problems with this.
    1) I’m not sure how to determine the difference between a link and a link to an image file. I’d like to apply different styles to each

    2) When I have an img src like this:
    <img src="http://www.aidslifecycle.org/images/alc5_logo.gif"/>
    It replaces it with this:
    <img src="<a href="http://www.aidslifecycle.org/images/alc5_logo.gif"/" rel="lightbox" class="ext" >http://www.aidslifecycle.org/images/alc5_logo.gif"/</a>>

    Can anyone help me out? I’m not very good with Regular expressions!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter blackc2004

    (@blackc2004)

    Can anyone please help me with this?!

    Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    That seems a bit complex. Might I suggest doing it in stages instead of trying to make one huge regular expression? Multiple simple regular expressions are faster than big giant ugly ones.

    Do a preg_replace for the images, then another for the links, and so on.

    Hello,

    looks a little bit complex to me, too. I just paste some modified old code I used in an old project:

    $regaus= '[^\">]';
    $search = array ("'<a[^>]*?http({$regaus2}*)\"'si", "'<img[^>]*?http({$regaus2}*)\"'si");
    $replace = array ("<a href=\"http\1\" style=\"xyz\"",
    "<img href=\"http\1\" style=\"xyz\"");
    $html = preg_replace($search, $replace, $html);

    It does not check wheter the link goes out to an external or internal link. Perhaps you can use preg_replace_recall to check.

Viewing 3 replies - 1 through 3 (of 3 total)

The topic ‘Regular Expression Help’ is closed to new replies.