How can one efficiently replace multiple occurrences of a specific pattern, like [img]...[/img], in a string using preg_replace in PHP?

When dealing with replacing multiple occurrences of a specific pattern like [img]...[/img] in a string using preg_replace in PHP, you can use the preg_replace function with a regular expression pattern that matches the desired pattern. By using the /g modifier at the end of the regular expression, you can replace all occurrences of the pattern in the string efficiently.

$string = "This is an example [img]image1.jpg[/img] [img]image2.jpg[/img] [img]image3.jpg[/img]";
$pattern = "/\[img\].*?\[\/img\]/";
$replacement = "[image]";
$new_string = preg_replace($pattern, $replacement, $string);
echo $new_string;