How can you prevent duplicating URLs that are already present in the text when extracting URLs in PHP?

When extracting URLs from text in PHP, you can prevent duplicating URLs that are already present by storing each extracted URL in an array and checking if a URL has already been added before inserting it. This way, you can ensure that each URL is unique and not duplicated.

$text = "Check out this website: http://example.com and also visit http://example.com for more information.";
$urls = array();

// Use regular expression to extract URLs from the text
preg_match_all('/\bhttps?:\/\/\S+\b/', $text, $matches);

foreach ($matches[0] as $url) {
    if (!in_array($url, $urls)) {
        $urls[] = $url;
    }
}

// Print the unique URLs
foreach ($urls as $url) {
    echo $url . "\n";
}