phpregexfunctionereg-replace

Replacing characters with smileys from echoed row


I can't figure this out and isn't my strong side of codeing ether.

As of right now it'll only print the first person and timestamp, not anything more.

<table cellpadding="0" cellspacing="0" width="100%">
<tr><td></td></tr>

<?php
include '../connection.php';  



$sql = "SELECT * 
FROM messagebox
INNER JOIN person
ON messagebox.sid = person.sid
ORDER BY messagebox.id DESC
LIMIT 20
";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query))
{
if ($switch=='1')
{
echo "<tr bgcolor=\"#FFFFFF\">";
$switch='0';
}
else
{
echo "<tr bgcolor=\"#F9F9F9\">";
$switch='1';
}

$elfstring = utf8_encode($row['shout']);

function smiley($elfstring) { 
      $elfstring = ereg_replace(":)","<img src=!.png alt=\"!\" >", $elfstring); 
      $elfstring = ereg_replace(":(","<img src=laugh.gif alt=\":D\" >", $elfstring); 
      $elfstring = ereg_replace(":p","<img src=tongue.gif alt=\":p\" >", $elfstring); 
      return $elfstrings; 

}
$messages = smiley($elfstring);

echo "";
   
echo "<td width=\"100\" valign=\"top\"><strong>" . $row['name'] . "</strong></td>";
 
echo "<td width=\"100\" valign=\"top\">" . "(" . $row['place'] .")</td>";
echo "<td width=\"70\" valign=\"top\">" . "" . date('H:i:s',strtotime ($row['timestamp'])) ."</td>";
echo "<td valign=\"top\">" . smiley($elfstrings) . "</td>";
echo "</tr>";

} 
?>

<tr>
<td>

</td>
</tr>
</table>

I know some parts of this code is deprecated, but the server using this is old and isn't up to date.

Thanks in advance for help.


Solution

    1. You can't declare a function multiple times. Move the function smiley(){ outside of your while loop.
    2. You should enable error reporting and monitor your error logs.
    3. You should indent each control block so you can easily tell where blocks end/start.
    4. If you don't need a regex/ aren't using one don't use a regex function. The ( and ) are special regex characters and will cause errors. Use str_replace because you are doing static replacements anyway.
    5. You can enclose strings in " or ', this can simplify string construction because you won't need to escape.

    So make the ending of your script:

    function smiley($elfstring) { 
          return str_replace(array(':)', ':(', ':p'),  
                             array('<img src="!.png" alt="!" >', '<img src="laugh.gif" alt=":D" >', '<img src="tongue.gif" alt=":p" >'), 
                              $elfstring); 
    }