How can you ensure that only clickable URLs remain in the text after extraction in PHP?

When extracting URLs from text in PHP, you can ensure that only clickable URLs remain by using regular expressions to match and extract valid URLs. This can be achieved by using the preg_match_all function to find all URLs in the text, and then replacing the non-URL text with the extracted URLs.

$text = "Check out my website at https://www.example.com and also visit https://www.example2.com";
preg_match_all('/https?:\/\/\S+/', $text, $matches);
foreach ($matches[0] as $url) {
    $text = str_replace($url, "<a href='$url'>$url</a>", $text);
}
echo $text;