How can preg_replace_callback be utilized to selectively remove links from a string in PHP?

To selectively remove links from a string in PHP, you can use the preg_replace_callback function along with a regular expression pattern to match URLs. Within the callback function, you can determine which links to keep or remove based on your criteria.

$string = "This is a sample text with a <a href='https://example.com'>link</a> and another link http://example.org.";
$pattern = '/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU';

$result = preg_replace_callback($pattern, function($matches) {
    // Check if the link should be removed based on your criteria
    if (/* add your condition here */) {
        return ''; // Remove the link
    } else {
        return $matches[0]; // Keep the link
    }
}, $string);

echo $result;