Php using preg_replace to include urls in links ..... sometimes ....: P

Possible duplicate:
How to add an anchor tag to url from PHP text input
Regular expression to match keyword outside of HTML <a> tag

Okay, so I use OsTicket (an email list system) and convert it to HTML emails going both internally and externally. It's hacked, but it works.

Well, at the moment there is a function called "clickableURLS" ....

  function clickableurls($text) {

        //Not perfect but it works - please help improve it. 
        $text=preg_replace('/([^(\'|")]((f|ht){1}tp(s?):\/\/)[-a-zA-Z0-9@:%_\+.~#?&;\/\/=]+[^(\'|")])/','<a href="\\1" target="_blank">\\1</a>', $text);
        $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")]www\.([a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+)(\/[^\/ \\n\\r]*)*[^('|\")])/",
                '\\1<a href="http://\\2" target="_blank">\\2</a>', $text);
        $text=preg_replace("/(^|[ \\n\\r\\t])([^('|\")][_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}[^('|\")])/",'\\1<a href="mailto:\\2" target="_blank">\\2</a>', $text);

        return $text;


As you can see, it basically uses the url (looks for http or https or www) and then adds a suitable mumbo jumbo there.


Now I have WYSIWYG installed .... so if one of our technicians is using WYSIWYG to create a RIGHT way link ... that automatically generates the code .... then the clickableurls function also finds the http that is already in the text and converts it to AGAIN ...

So I'm basically trying to find the best way to handle this. I needed BIG options .. and was thinking maybe doing an IF statement, but wouldn't preg_replace make a little more sense?

Any thoughts? Thanks again for overflowing the community!


source to share

1 answer

I can try to help you translate what you have in the first pre-generated pre-generation ().
This is the best I can do because I do not know your intentions. I have extrapolated some intent,
but it is up to you to determine this.

When the regex is complex, block formatting makes it easy to see the complexity.


(                                    # Capture group 1
    [^'"]                                # Consume a character that is not single nor double quote
    (                                    # Capture group 2
      (?:ftp|https?):                       # Either ftp, OR http (optional s) string literal
      //                                    # Literl double forward shashes
    )                                    # End capt grp 2
    [-a-zA-Z0-9@:%_+.~#?&;/=]+           # 1 or more (greedy) of the characters in this class
    [^'"]                                # Consume a character that is not single nor double quote
)                                    # End capt grp 1




All Articles