You could change the condition to make sure the first character is one that you specify. As usual, there are a number of different ways to do it so the following example may or may not be suited to your script:
PHP Code:
<?php
$str = 'Somewhere in the Middle East.';
// If first character is one of B, E, F, G, M or S.
if (strpbrk($str[0], 'BEFGMS'))
{
$img = sprintf('<img src="pictures/%s.jpg" alt="%s">', strtolower($str[0]), $str[0]);
// Replace first character with <img> tag
$str = substr_replace($str, $img, 0, 1);
}
echo $str;
?>
Off Topic:
You'll probably never remember the name of the
strpbrk function, hence the comment in the code. The function simply returns the portion of the subject string (first argument) starting at one of the characters provided in the second argument. If none of the characters are found, it will return
FALSE (which is useful for us). For example,
strpbrk("foo", "aeiou") will return "
oo" and
strpbrk("abcdef","xyz") will return
FALSE. This is useful to us because a) we're only using a single character as the subject string (i.e.,
S in the previous posts) and b) letters get evaluated as
TRUE in
if statements. In summary, if our string starts with one of those letters then the body of the
if statement will be executed.
P.S. Not particularly off-topic, but a pleasant aside.
Bookmarks