How to convert a URL inside a string to a hyperlink in PHP

1 Answer

0 votes
function convertUrlsToLinks($text) {
    return preg_replace('/(https?:\/\/[^\s]+)/', '<a href="$1">$1</a>', $text);
}

$str = "This is my website check it out https://www.collectivesolver.com";
$result = convertUrlsToLinks($str);

echo $result;



/*
run:

This is my website check it out <a href="https://www.collectivesolver.com">https://www.collectivesolver.com</a>

*/

 



answered May 2, 2025 by avibootz
...