Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]

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>

1 comment:

Bottom Ad [Post Page]