SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    ri
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    trouble getting preg_replace to work properly, please help

    hi-

    i have some strings that are in a format like this:
    "[L$i]<a href="randomlinkshere"></a>"

    the $i is a variable which can change. two examples i might have are:
    "[L1]<a href="randomlink1"></a>"
    "[L2]<a href="randomlink2"></a>"

    what i need to do it change the </a> at the end to [/L$i]
    so my results examples would look like:
    "[L1]<a href="randomlink1">[/L1]"
    "[L2]<a href="randomlink2">[/L2]"


    it's going to be in a loop and i know it needs to look something like this:
    for ($i=0; $i<5; $i++)
    preg_replace("[L$i]wildcard</a>", [L$i]wildcard[/L$i], string);


    how can i do this with preg_replace? i know i can do it somehow but i have not used regular expressions before and after reading through the docs and trial and error the last hour i'm very frustrated. it's tricky because i need to use the $i php variable in my preg_replace and i know $ is one of the syntax characters so i need to escape it and then i need to match a wildcard... i'm a mess and stuck

    i really appreciate any help

    thanks

  2. #2
    SitePoint Enthusiast
    Join Date
    Aug 2004
    Location
    earth
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am not sure I understand you question 100% but you can try this:

    Code:
    $string = preg_replace('|(\[(L'.$i.'\])<a href=".*?">)</a>|', "$1[/$2", $string);

  3. #3
    SitePoint Wizard Chris82's Avatar
    Join Date
    Mar 2002
    Location
    Osnabrück
    Posts
    1,003
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    sax140: almost you need to change the $i to match a number and it should work

    PHP Code:
    $text '[L1]<a href="randomlink1"></a>
    [L2]<a href="randomlink2"></a>'
    ;

    $text preg_replace('#\[L(\d+?)\](.+?)</a>#'"[L$1]$2[/L$1]"$text);

    echo 
    htmlentities($text); 
    Also, you don't need a for-loop anymore.

  4. #4
    SitePoint Enthusiast
    Join Date
    Aug 2004
    Location
    earth
    Posts
    37
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, I put the $i so it could plug in directly in his loop.
    But you are right, the loop is not needed at all if he was to change all occasions.

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2004
    Location
    ri
    Posts
    82
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    you understood it well enough cause it worked!

    thanks a bunch!


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
  •