Page 1 of 1

Evaluating every character of a string?

Posted: Sat Jul 30, 2005 7:14 pm
by loosus
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.

Posted: Sat Jul 30, 2005 9:20 pm
by feyd
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(
 '.'=&amp;gt;'period',
);
$a = ord('a');
$z = ord('z');
$ca = ord('A');
$cz = ord('Z');
for($i = 0, $j = strlen($str); $i &amp;lt; $j; $i++)
{
  $ch = $str{$i};
  $o = ord($ch);
  if(isset($map&#1111;$ch]))
  {
    $file = $map&#1111;$ch];
  }
  elseif($a &amp;lt;= $o &amp;amp;&amp;amp; $o &amp;lt;= $z or is_numeric($ch))
  { //  lower case letter or number
    $file = $ch;
  }
  elseif($ca &amp;lt;= $o and $o &amp;lt;= $cz)
  { //  upper case letter
    $file = 'c'.$ch;
  }
  else
  { //  unknown character, ignore it?
    continue;
  }
  echo '&amp;lt;img src=&quote;'.$file.'.gif&quote; /&amp;gt;';
}

Posted: Sun Jul 31, 2005 4:28 am
by onion2k
Simplified version..

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\">";
  }
}
Feyd's deals with odd characters better, but if you're not worried about that mine is easier to understand.