Skip to content
PHP Logo

How can you ensure that only the first letter of a text is replaced with an image using str_replace in PHP?

To ensure that only the first letter of a text is replaced with an image using str_replace in PHP, you can use a combination of functions such as substr, str_replace, and concatenation. By extracting the first letter of the text using substr, replacing it with an image using str_replace, and then concatenating the rest of the text, you can achieve the desired outcome.

php
$text = "Hello world";
$firstLetter = substr($text, 0, 1);
$restOfText = substr($text, 1);
$image = "<img src='image.jpg'>";
$newText = $image . $restOfText;

echo $newText;