Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you obtain only the URL from data [duplicate]

I have a slight issue that I am in need of help with.

Say if $post['text'] was equal to data like: "https://stackoverflow.com/blah?blah is such a cool website", how would it be possible to make just the URL bit in a type tag...

So the end HTML result would be somthing like

<p><a href="https://stackoverflow.com/blah?blah">https://stackoverflow.com/blah?blah</a> is such a cool website</p>

I am a bit of a noob. I'm actually a 14 year old kid and still kinda new to code, but I loveee it!

like image 917
CALI1198 Avatar asked Oct 04 '22 13:10

CALI1198


1 Answers

You can use regular expersion.

function make_hyperlink($text)
{
    // match protocol://address/path/
    $text = preg_replace("{[a-zA-Z]+://([.]?[a-zA-Z0-9_/-])*}", "<a href=\"\\0\" target='_blank'>\\0</a>", $text);

    // match www.something
    $text = preg_replace("{(^| )(www([.]?[a-zA-Z0-9_/-])*)}", "\\1<a href=\"http://\\2\" target='_blank'>\\2</a>", $text);

    // return $text
    return $text;
}

echo make_hyperlink('http://stackoverflow.com/blah?blah');

Use above function. It will replace URL from a simple url text.

like image 140
Raju Singh Avatar answered Oct 07 '22 19:10

Raju Singh