Replacing part of link with regexp

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Martijn Berendsen

    Replacing part of link with regexp

    Hello!

    Example:
    <a href="www.abc.c om">ABC</a>
    <a href="www.xyz.c om">www.xyz.com </a>

    I'm looking for a script that replaces the part within the HTML tag
    (www.abc.com and www.xyz.com) with another link (in my case a
    redirect), without affecting the part with "www.xyz.co m: enclosed by
    the tags.

    I've tried something myself which replaces the url's, but all strings
    that resemble an url

    function replaceUrls($te xt)
    {
    global $BASE_URL;

    $pattern = "[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]";
    $replacement = "\\0";
    $text = eregi_replace($ pattern, $replacement, $text);

    $endoftext = 0;

    while (!$endoftext)
    {
    $start = strpos($text, "");
    $end = strpos($text, "
    ");

    if (($start) && ($end))
    {
    $url = substr($text, $start + 5, $end - $start - 5);

    $newurl = "redirect.php?u rl=$url";
    $oldurl = "" . $url . "";

    $text = str_replace($ol durl, $newurl, $text);
    }
    else
    {
    $endoftext = 1;
    }
    }
    return $text;
    }

  • Hero Wanders

    #2
    Re: Replacing part of link with regexp

    Hello!
    [color=blue]
    > <a href="www.abc.c om">ABC</a>
    > <a href="www.xyz.c om">www.xyz.com </a>
    >
    > I'm looking for a script that replaces the part within the HTML tag
    > (www.abc.com and www.xyz.com) with another link (in my case a
    > redirect), without affecting the part with "www.xyz.co m: enclosed by
    > the tags.[/color]

    This should work:

    <?php

    $link = '<a href="http://www.google.com" target="_bla">f oobar</a>';
    $my_url = 'http://www.example.com/redirect.php?ur l=$1';

    echo preg_replace('/(?<=\<a href\=\")([^\"]+)(?=\")/', $my_url, $link);

    ?>

    Of course $link could be any text containing links.

    Greetings,
    Hero Wanders

    Comment

    Working...