SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2006
    Posts
    65
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    In need of help with preg_replace

    Hello all. I'm attempting to make an HTML fetcher type of script. So far I'm doing good, but I have stumbled across a problem: I'm trying to replace every link in the document with a link going through my site (for statistics). Something like this:

    <a href="http://www.yahoo.com" title="...">
    with
    <a href="http://www.site.com/fetch?http://www.yahoo.com" title="...">

    Sadly, I'm no good with Regex and don't expect to even remotely grasp the syntax anytime soon. So anyone mind showing me the proper regex to use for this kind of script?

    Oh and I already know that a number of sites don't use the full URL, but rather something like /dogs/index.php to navigate through the site, but I think I can handle that on my own.

    Thanks in advance.

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    $re = "~<a([^<>]+?)href=([\'\"])~si";
    matches "<a" then any number of arbitrary chars (to handle <a title=... href=...) then "href" and a quote. The replacement string should look like this
    Code:
    $repl = "<a$1href=$2http://www.site.com/fetch?";
    Putting it all together
    Code:
    $new = preg_replace($re, $repl, $html);

  3. #3
    SitePoint Enthusiast Salkcin's Avatar
    Join Date
    Jun 2006
    Location
    Sweden
    Posts
    73
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here´s another way:

    PHP Code:
    preg_replace('/(?<=<a href=")(.*?")/''http://www.site.com/fetch?\\1'$string); 

  4. #4
    SitePoint Enthusiast
    Join Date
    Oct 2006
    Posts
    65
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you tons, guys (or gals). I'll be sure to acknowledge you two (and this forum in general) with proper credit!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •