How can URLs in a string be recognized and replaced in PHP?

To recognize and replace URLs in a string in PHP, you can use the preg_replace function with a regular expression pattern to match URLs. You can use the following regular expression pattern to match URLs in a string: '/\b(?:https?|ftp):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|]/'. Then, you can use preg_replace to replace the URLs with a desired replacement string.

$string = "This is a sample text with a URL https://www.example.com and another URL http://www.test.com";

$pattern = '/\b(?:https?|ftp):\/\/[-a-zA-Z0-9+&@#\/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#\/%=~_|]/';
$replacement = 'URL_REPLACED';

$result = preg_replace($pattern, $replacement, $string);

echo $result;