Friday, 31 May 2019

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string

Using PHP

$string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world. 
CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg  
CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be';


$string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string);







Using Javascript

<script>
function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    return replacedText;
}
var textTest = 'Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. He is a currently a professor of physics at Palomar College in San Marcos, CA. Additionally, he is the Founder & President of H.E.R. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world. CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg  CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be';
console.log(linkify(textTest));

</script>

0 comments:

Post a Comment