如何在PHP中自动替换单词

时间:2011-11-21 14:46:08

标签: php string str-replace

我有一个关于mysql数据库的表,如下所示:

|word|replace|
--------------
|sa  | sap   |
|ri  | sip   |
|na  | sup   |
--------------

因此,如果我提交单词:sarina,则会自动更改:sapsipsup

我试过这样:

$word= array("sa", "ri", "na");
$replace = array("sap", "sip", "sup");

$str = str_split("sarina",2);
$result = str_replace($word, $replace, $str);
echo $result;

但是,它不是动态的,我的意思是......我应该首先将“sarina”拆分为2个字符。 如何使任何单词自动简单?

提前致谢。

1 个答案:

答案 0 :(得分:5)

您基本上通过标记问题str-replace来回答自己。您需要做的就是查询数据库中的所有条目,将它们放入两个数组中,然后使用这两个数组在字符串上运行str_replace()。像这样:

$result = mysql_query('SELECT `word`, `replace` FROM `table`');
$find = array();
$replace = array();
while ($row = mysql_fetch_assoc($result)) {
   $find[] = $row['word'];
   $replace[] = $row['replace'];
}
$yourstring = str_replace($find, $replace, $yourstring);

注意:此处没有错误处理等...不要使用该代码,仅作为灵感。