preg replace - replace links

Discussion in 'PHP' started by pairbrother, Jun 17, 2007.

  1. #1
    Hi there,

    I have a a large number of pages in which I want to replace parts of links within it. Ill give an example
    This is the html I am getting from a function:
    <p>In most <a href=\"/toreplace/Bird\" title=\"Bird\">birds</a> and <a href=\"/toreplace/Reptile\" title=\"Reptile\">reptiles</a>, an <b>egg</b> is the <a href=\"/toreplace/Zygote\" title=\"Zygote\">zygote</a>, resulting from <a href=\"/toreplace/Fertilization\" title=\"Fertilization\">fertilization</a> of the <a href=\"/toreplace/Ovum\" title=\"Ovum\">ovum</a>. It nourishes and protects the <a href=\"/toreplace/Embryo\" title=\"Embryo\">embryo</a>.
    Code (markup):
    I want to replace all the links in it for ex:
    <a href=\"/toreplace/Bird\" title=\"Bird\">birds</a> 
    Code (markup):
    with
    <a href=\"/Bird.html\" title=\"Bird\">birds</a> 
    Code (markup):
    That is I want to remove the text "toreplace" and add a .html at the end of the link.

    I hope this is possible using php regex and I am at the right place amongst the right people.
    Any help would be appreciated. Thanks a lot
     
    pairbrother, Jun 17, 2007 IP
  2. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #2
    Here is a simple regex pattern. Not perfect but for your situation, this should be fine:
    href="/toreplace/([^"]+)" ==> /$1.html

    To do it through PHP:
    preg_replace('~href="/toreplace/([^"]+)"~', '/$1.html', $html);
    PHP:
     
    krt, Jun 17, 2007 IP
    pairbrother likes this.
  3. pairbrother

    pairbrother Well-Known Member

    Messages:
    386
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    110
    #3
    Ammazing! Thanks krt
    A little editing was required though :)
    preg_replace('~href="/toreplace/([^"]+)"~', 'href="/$1.html"', $html);
    Code (markup):
     
    pairbrother, Jun 18, 2007 IP
  4. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #4
    Great, and glad you got that sorted out (and reminding me yet again to be more careful with the code I write :p)
     
    krt, Jun 18, 2007 IP