What are common pitfalls when using preg_replace() in PHP for converting URLs to hyperlinks?
One common pitfall when using preg_replace() in PHP to convert URLs to hyperlinks is that it may not handle URLs with special characters or query parameters correctly. To solve this issue, you can use the preg_replace_callback() function along with a regular expression that captures the URL and then construct the hyperlink tag dynamically inside the callback function.
$text = "Check out my website at https://www.example.com";
$text = preg_replace_callback(
'/https?:\/\/\S+/',
function($matches) {
return '<a href="' . $matches[0] . '">' . $matches[0] . '</a>';
},
$text
);
echo $text;