How can PHP developers efficiently handle image retrieval and display from a database using preg_replace()?
When retrieving images from a database in PHP, developers can use preg_replace() to replace image placeholders in the text with actual image tags. This allows for efficient handling of image retrieval and display within the content. By using preg_replace() with a regular expression pattern to identify placeholders and replace them with image tags, developers can streamline the process of displaying images from a database.
// Retrieve text content with image placeholders from the database
$text = "This is a sample text with an image placeholder: [IMG:1234].";
// Define a regular expression pattern to match image placeholders
$pattern = '/\[IMG:(\d+)\]/';
// Replace image placeholders with actual image tags
$text = preg_replace($pattern, '<img src="getImage.php?id=$1" alt="Image $1">', $text);
// Display the text with images
echo $text;