What are some common methods to recognize and convert URLs in a PHP textarea field?

When working with a textarea field in PHP, you may encounter the need to recognize and convert URLs entered by users into clickable links. One common method to achieve this is by using regular expressions to identify URLs in the text and then replacing them with HTML anchor tags. This allows the URLs to be displayed as clickable links when the text is rendered on a webpage.

<?php
function convertUrlsToLinks($text) {
    $pattern = '/((http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)/i';
    $replacement = '<a href="$1" target="_blank">$1</a>';
    $text = preg_replace($pattern, $replacement, $text);
    return $text;
}

// Example usage
$text = "Check out this website: https://www.example.com";
$convertedText = convertUrlsToLinks($text);
echo $convertedText;
?>