用PHP替换多个字符串中的某些单词

时间:2011-12-11 03:09:42

标签: php mysql

我有一个字符串数据库,一个单词数据库及其更正。我需要找到字符串中的单词并用它们的更正替换它们。我无法弄清楚如何做到这一点并让它循环遍历数据库中的所有字符串。我需要帮助。

我正在思考以下伪代码“

//while loop to grab all the strings from db

//add all the words to look for to an array
//add all of the word replacements to an array

//preg replace or str replace the words with the replacements in the string.

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我会看一下使用strtr。这将一个字符串(句子)作为第一个参数,一个键/值对的数组作为替换文本。

<?php

$sentence = "The quick brown fox jumps over the lazy dog";
$replacements = array("quick" => "fast", "brown" => "white", "fox" => "hair");

echo strtr($sentence, $replacements);

收率:

The fast white hair jumps over the lazy dog

如果您不熟悉它,我也会在Tokenization上阅读。它可以帮助您理解其工作原理背后的基础逻辑。

答案 1 :(得分:0)

如果您将所有字符串放入数组$orig,将所有单词放入数组$words,并将所有更正放入数组$corrections,则可以这样做:

$corrected = str_replace($words, $corrections, $orig);

Here是关于str_replace的文档。

相关问题