preg_replace - how to strip all links

Discussion in 'PHP' started by redhits, Oct 29, 2009.

  1. #1
    I would like to strip all links from a website, and change all links to #.

    how i can change all links like a href="http://digitalpoint.com" toan simple a href="#" ?!
     
    redhits, Oct 29, 2009 IP
  2. AsHinE

    AsHinE Well-Known Member

    Messages:
    240
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    138
    #2
    Something like that:
    
    $text = preg_replace('/href=".+?"/sm', 'href="#"', $text);
    
    PHP:
    Will work if quotes are ", if single qoutes:
    
    $text = preg_replace('/href=\'.+?\'/sm', 'href="#"', $text);
    
    PHP:
     
    AsHinE, Oct 29, 2009 IP
  3. organicCyborg

    organicCyborg Peon

    Messages:
    330
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #3
    The link doesn't have to be in single or double quotes though, it can be directly after the "a href=" statement and still be valid.

    This may be a more elegant solution that will also remove any javascript embedded in the link.

    
    <?php
    $text = <<<END
    	this <a href="test.html">is</a> 
    	<a href='test.html'>a</a> 
    	<a href="test.html">test</a> !!! 
    END;
    
    print $text . "<br />";
    
    $text = preg_replace('/<a href=.+?>/', '<a href="#">', $text);
    
    print $text;
    ?>
    
    Code (markup):
     
    organicCyborg, Oct 29, 2009 IP
  4. AsHinE

    AsHinE Well-Known Member

    Messages:
    240
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    138
    #4
    AFAIK there can be alteration in REGEX, but I don't know regex so much to use it, so problem with single double or no quotes can be solved with 1 preg_replace.

    I suppose this code
    
    $text = preg_replace('/<a href=.+?>/', '<a href="#">', $text);
    
    PHP:
    will not work with links like this
     
    AsHinE, Oct 29, 2009 IP
  5. redhits

    redhits Notable Member

    Messages:
    3,023
    Likes Received:
    277
    Best Answers:
    0
    Trophy Points:
    255
    #5
    I code all my codes like this ..

    $search='#(<BASE HREF=")(.*)(wstub.archive.org/">)#e';
    $data = preg_replace($search,"('')",$data);


    I mean i code the search_replace like this:

    (begin)(match)(end)

    Can somebody translate this to me in the () () () , because you only push me deeper into darkness...


    how '/<a href=.+?>/', will look in ()(.*)() ?!

    (href=".*)(.*)(") ?!
     
    redhits, Oct 29, 2009 IP