What are the best practices for efficiently extracting image URLs from a given text using PHP?

When extracting image URLs from a given text using PHP, one efficient approach is to use regular expressions to search for URLs that end with common image file extensions such as .jpg, .png, or .gif. By using preg_match_all function with a regex pattern, we can extract all image URLs from the text. Additionally, it's important to sanitize and validate the extracted URLs to ensure they are valid image links.

$text = "Lorem ipsum dolor sit amet, <img src='image.jpg'> consectetur adipiscing elit. <img src='photo.png'> Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $text, $matches);

$imageUrls = $matches[1];

foreach ($imageUrls as $imageUrl) {
    // Validate and sanitize the extracted image URL
    if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
        echo $imageUrl . "<br>";
    }
}