Log in

View Full Version : String Replacement



Titan85
04-13-2007, 07:09 PM
Ok, I am trying to make a string replacer to do what forums do with replacing BBC code and smilies. Here is what I have:
<?php require('config.php'); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Posts</title>
</head>

<body>
<?php
$get = mysql_query("SELECT * FROM `messages` ORDER BY id DESC") or die (mysql_error());
while ($p = mysql_fetch_array($get)) {

$get_replace = mysql_query("SELECT * FROM `replacements`") or die ('Error getting replacements! <br />' .mysql_error());
while ($r = mysql_fetch_array($get_replace)) {
extract($r);
$post = str_replace($tbefore, $tafter, $p['message']);
}

echo '
<b>'.$p['title'].'</b>
<br />
'.$post.'';
}

?>
</body>
</html>
I have 3 things to replace in the database, but it only replaces one of them. I thought that this would be fixed with the while statement, but still nothing. Any ideas? thanks

Twey
04-13-2007, 08:23 PM
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />That's the wrong MIME type for XHTML.

Your problem is here:
$post = str_replace($tbefore, $tafter, $p['message']);Say you have replacements:
+---------+--------+
| tbefore | tafter |
+---------+--------+
| :) | smile |
| :( | frown |
+---------+--------+and a post (stored in $p['message']):
Lorem :) ipsum dolor :( sit amet...That line will be executed once for each replacement. So, first of all, it takes $p['message'], replaces each :) with smile:
Lorem smile ipsum dolor :( sit amet...... and stores the result in $post. Then, it takes $p['message'] again (which is unmodified: remember, the result of the last loop was stored in $post), and applies the next replacement:
Lorem :) ipsum dolor frown sit amet...You want to store the results back into $p['message']:
$p['message'] = str_replace($tbefore, $tafter, $p['message']);