Reputation: 3686
I am getting these random synopsis details as a string, but the odd one or two contain links to URL's etc. These are raw strings and contain no html tags, just pure strings.
So the urls within the strings would simply be http://www...ect etc
or even just www.name... etc
.
What I'm trying to do is to convert these into clickable links, so when they output to the browser they actually are links rather than a string url that a user would have to copy and paste etc.
An example of the string would be:
Lorem ipsum dolor sit amet consectetur adipisicing elit. Animi possimus nisi a quis, voluptas adipisci asperiores, earum aut totam sequi necessitatibusrepellat, quasi labore molestiae. Laboriosam quis vitae unde http://www.websitename.com?title=oy96 natus.earum aut totam sequi necessitatibus repellat, quasi labore molestiae. Laboriosam quis vitae unde natusearum aut totam sequi necessitatibus repellat, quasi labore molestiae. Laboriosam quis vitae unde natus
Would be good to turn http://www.websitename.com?title=oy96
into a clickable link with just the domain name.www.websitename.com
Upvotes: 1
Views: 184
Reputation: 19366
Just have written the perfect solution to your problem:
function webAddressesToHTML($text,$label_strip_params=false,$label_strip_protocol=true) {
$webAddressToHTML = function ($url) use ($label_strip_params,$label_strip_protocol) {
$label = $url;
if($label_strip_params) {
$label = rtrim(preg_replace('/\?.*/', '',$label),"/");
}
if($label_strip_protocol) {
$label = preg_replace('#^https?://#', '', $label);
}
return '<a href="'.((!preg_match("~^(?:f|ht)tps?://~i", $url)) ? "http://".$url : $url).'">'.$label.'</a>';
};
preg_match_all('@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@',$text,$matched_urls);
return str_replace($matched_urls[0],array_map($webAddressToHTML,$matched_urls[0]),$text);
}
See the example:
$demo = "After the latest show, we went to www.example.com and made some trouble online. https://www.letsfail.net/?a=b gave us their support and also netjunkies.sample is involved. Finally we are in!";
var_dump(webAddressesToHTML($demo));
Output:
string(302) "After the latest show, we went to <a href="http://www.example.com">www.example.com</a> and made some trouble online. <a href="https://www.letsfail.net/?a=b">www.letsfail.net/?a=b</a> gave us their support and also <a href="http://netjunkies.sample">netjunkies.sample</a> is involved. Finally we are in!"
Depending on how you want to have your web address label, just set the optional parameters to true
or false
. If you really want to strip get parameters depends on your use case.
Upvotes: 0