Let's say that I had this string:
Hi.
Is there any way I can do something for every character of the string?
Here's what I'm specifically trying to do: convert each character of a string to an appropriate image, so that the above example would become this output:
<img src="h.gif"><img src="i.gif"><img src="period.gif">
Thanks in advance.
Evaluating every character of a string?
Moderator: General Moderators
- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
use a for loop to iterate over each character in the string and an associative array mapping to help convert the character to a filename to use
Code: Select all
$str = 'hi.';
$map = array(
'.'=&gt;'period',
);
$a = ord('a');
$z = ord('z');
$ca = ord('A');
$cz = ord('Z');
for($i = 0, $j = strlen($str); $i &lt; $j; $i++)
{
$ch = $str{$i};
$o = ord($ch);
if(isset($mapї$ch]))
{
$file = $mapї$ch];
}
elseif($a &lt;= $o &amp;&amp; $o &lt;= $z or is_numeric($ch))
{ // lower case letter or number
$file = $ch;
}
elseif($ca &lt;= $o and $o &lt;= $cz)
{ // upper case letter
$file = 'c'.$ch;
}
else
{ // unknown character, ignore it?
continue;
}
echo '&lt;img src="e;'.$file.'.gif"e; /&gt;';
}Simplified version..
Feyd's deals with odd characters better, but if you're not worried about that mine is easier to understand.
Code: Select all
for ($x=0;$x<strlen($string);$x++) {
if ($string{$x} == ".") {
echo "<img src=\"period.gif\">";
} else {
echo "<img src=\"".strtolower($string{$x}).".gif\">";
}
}