9

Say i have a string of text such as

$text = "Hello world, be sure to visit http://whatever.com today";

how can i (probably using regex) insert the anchor tags for the link (showing the link itself as the link text) ?

1

2 Answers 2

24

You can use regexp to do this:

$html_links = preg_replace('"\b(https?://\S+)"', '<a href="$1">$1</a>', $text);
Sign up to request clarification or add additional context in comments.

4 Comments

your answer worked like a charm but if i wanna check also presence of www how would i do it?
@Sarah unless you want to specifically target all url containing only www, this should catch those. If you need to check for www, then just add www\. like so: \b(http://www\.\S+) and that should catch only URL with www.
If the document contains non-ascii characters (like asian languages), you can replace the "\S+" for: "[0-9a-zA-Z-._~:/?#[]@!$&'()*+,;=]+" if the URLs are only ascii characters (othewise don't change it)
To include https:// too: - $html_links = preg_replace('"\b(http\S+)"', '<a href="$1">Link</a>', $text);
6

I write this function. It replaces all the links in a string. Links can be in the following formats :

The second argument is the target for the link ('_blank', '_top'... can be set to false). Hope it helps...

public static function makeLinks($str, $target='_blank')
{
    if ($target)
    {
        $target = ' target="'.$target.'"';
    }
    else
    {
        $target = '';
    }
    // find and replace link
    $str = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.~]*(\?\S+)?)?)*)@', '<a href="$1" '.$target.'>$1</a>', $str);
    // add "http://" if not set
    $str = preg_replace('/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i', '<a href="http://$1" '.$target.'>', $str);
    return $str;
}

Edit: Added tilde to make urls work better https://regexr.com/5m16v

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.