Nah, I'm not sick of regex at all.

Discussion in 'PHP' started by blueparukia, Oct 2, 2008.

  1. #1
    All I want to do is something simple. :(

    I want to find all links in the text and replace them with a word.

    Say I have a text that reads:

    
    Hello everyone, this site is google: www.google.com and this site is yahoo!: http://yahoo.com.
    
    I rock.
    
    Code (markup):
    That should become:

    
    Hello everyone, this site is google: LINK and this site is yahoo!: LINK
    
    I rock.
    
    Code (markup):
    I currently have:
    
    preg_replace('~(http://|ftp://|https://|www\.)(.*)~i','LINK',$message)
    
    PHP:
    Cheers,

    Josh
     
    blueparukia, Oct 2, 2008 IP
  2. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #2
    hmm.. the (.*) will match the rest of the message because you didn't say what it should match up to..
    try replacing it with (.*? ) this should match to the first space after the url

    preg_replace('~(http://|ftp://|https://|www\.)(.*? )~i','LINK',$message)
    PHP:
     
    lui2603, Oct 2, 2008 IP
  3. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #3
    While it seems to work, for this string:

    
    www.google.com
    Or
    https://meh.com
    
    Code (markup):
    It replaces the entire string...because nothing is in there to do newlines. It works fine if you stick a space at the end of the line though
     
    blueparukia, Oct 2, 2008 IP
  4. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Not sure if I understand you properly but to match new lines you can put an s at the end of the regex ;)
    preg_replace('~(http://|ftp://|https://|www\.)(.*? )~si','LINK',$message)
    PHP:
     
    lui2603, Oct 3, 2008 IP
  5. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #5
    Nope.

    I currently have:

    
    preg_replace('~(http://|ftp://|https://|www\.?)(.*)([ \t\r\n\v\f]?)~is', 'LINK$3' , $message);
    
    PHP:
    To match all links, and against this string:

    
    www.google.com
    Or
    https://meh.com
    
    Code (markup):
    Or anything similar, it replaces the ENTIRE string with "LINK".

    Thank you.
     
    blueparukia, Oct 9, 2008 IP