How can you avoid potential pitfalls when using preg_replace with multiple images in a text?

When using preg_replace with multiple images in a text, potential pitfalls can arise if the regular expression used is not specific enough, leading to unintended replacements. To avoid this, you can use a more precise regular expression pattern that targets only the specific image tags you want to replace. Additionally, you can use the preg_replace_callback function to handle each match individually and apply custom logic to prevent unwanted replacements.

// Sample code snippet to avoid pitfalls when using preg_replace with multiple images in a text
$text = "This is an example <img src='image1.jpg'> text with <img src='image2.jpg'> multiple <img src='image3.jpg'> images.";

// Define a regular expression pattern to match image tags
$pattern = "/<img src='(.*?)'>/";

// Use preg_replace_callback to handle each match individually
$result = preg_replace_callback($pattern, function($match) {
    // Add custom logic here if needed
    $imagePath = $match[1];
    
    // Perform replacement or other operations
    return "<img src='" . $imagePath . "'>";
}, $text);

echo $result;