Another preg_replace help

Discussion in 'PHP' started by mehdi, Aug 18, 2009.

  1. #1
    Hello,
    I am currently using following code to get Links Title:

    preg_replace('#<a(.*?)href=([\'"])([^\2]+?)\2([^>]*>)(.+?)</a>#is', '<a$1href=$2$3$2$4$5 ($3)</a>', $str);
    Code (markup):
    It shows all the links as:
    <a href="http://link.com">Link (http://link.com)</a>

    Can you help me to make it like that, if link contains class tag, like class="link" then it will display as
    <a href="http://link.com" class="link">Link (http://link.com) (class: link)</a>

    Thanks!! :)
     
    mehdi, Aug 18, 2009 IP
  2. superdav42

    superdav42 Active Member

    Messages:
    125
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #2
    The only way I know how to would be just to add another regex to catch the links that have classes.
    
    preg_replace('#<a(.*?)href=([\'"])([^\2]+?)\2(.*?)class=([\'"])([^\5]+?)\5([^>]*>)(.+?)</a>#is',
    '<a$1href=$2$3$2$4class=$5$6$5$7$8 ($3) (class:$6)</a>',
    $str);
    
    PHP:
    Someone else might know how to do it with just one regex but as long as you put this one first in your code and then the one you already have it should work the way you want.

    BTW, I don't think these would work if you had a tag that was not xhtml ie:
    <a href=google.com>google</a> because your regex is expecting it to have quotes. Hopefully you don't have to worry about this case.
     
    superdav42, Aug 18, 2009 IP
    mehdi likes this.
  3. mehdi

    mehdi Peon

    Messages:
    258
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you that works great :)
     
    mehdi, Aug 19, 2009 IP