preg_match url replace

Discussion in 'PHP' started by redhits, Oct 10, 2007.

  1. #1
    How i can add something after each URL ?!

    like replace
    <a href="http://website.com"> Text with something like

    <a href="http://website.com"> text Link to : http://website.com ?!


    my problem is that <a href="http://website.com">
    can also be <a href="http://website.com class=link target_new , so it's a little bite hard to do it with explode then rebuild the html code, so i must to use some magic like preg replace
     
    redhits, Oct 10, 2007 IP
  2. redhits

    redhits Notable Member

    Messages:
    3,023
    Likes Received:
    277
    Best Answers:
    0
    Trophy Points:
    255
    #2
    I try an code as:

    $website=" href=softgroups.com > caca maca /a ;
    href softgroups.com > softgroups /a

    ";
    $code="$1=<b>Link</b>";
    $pattern='/\s(href)=["\']/i';
    $website=preg_replace($pattern,$code,$website);



    but i want to add some text after the ending > :( so i don't known how to do it...
     
    redhits, Oct 10, 2007 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    
    $text = preg_replace(
    	'/<a([^>]+href=[\'"]?([^"\'\s]+)[^>]+)>(.*?)<\/a>/si',
    	'<a$1>$3</a> <a href="http://website.com">Website</a>',
    	$text
    );
    
    PHP:
    If I understood you correctly.
     
    nico_swd, Oct 10, 2007 IP
  4. Mong

    Mong ↓↘→ horsePower

    Messages:
    4,789
    Likes Received:
    734
    Best Answers:
    0
    Trophy Points:
    235
    #4
    That text would be 'anchor text' ?
     
    Mong, Oct 10, 2007 IP
  5. scriptillusion

    scriptillusion Peon

    Messages:
    3,229
    Likes Received:
    129
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Maybe this preg_replace php snippet will help you figure out what to do.

    
    <?php
    $link = '<a href="http://website.com">click here</a>';
    $link = preg_replace('%<a href=(.*?)</a>%sim', '<a href=$1 Extra Text</a>', $link);
    echo $link;
    ?>
    
    PHP:
     
    scriptillusion, Oct 10, 2007 IP
  6. redhits

    redhits Notable Member

    Messages:
    3,023
    Likes Received:
    277
    Best Answers:
    0
    Trophy Points:
    255
    #6
    I will test this later on , thx
     
    redhits, Oct 11, 2007 IP