str_replace()与foreach,大写和精确的单词匹配

时间:2014-02-01 19:37:16

标签: php regex arrays string str-replace

我的代码是:

$db = &JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('old', 'new')))
      ->from($db->quoteName('#__words'));
$db->setQuery($query);
$results = $db->loadAssocList();
$find = array();
$replace = array();
foreach ($results as $row) {
 $find[] = $row['old'];
 $replace[] = $row['new'];
}
$newstring = str_replace($find, $replace, $oldstring);
echo $newstring;

此代码将“旧”列中的所有单词替换为“new”列中的单词。但是有两个问题。首先它是有效的,如果找到和替换的单词都具有相同的情况(上部或下部),但我需要它将工作,无论情况,即数据库只有小写,但如果前端的查找单词有大写,被替换的单词也必须大写。其次,我需要精确的单词匹配。提前谢谢!

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

$oldstring = 'The cat and the dog are flying into the kitchen. Dog. Cat. DOG. CAT';

$results = array( array('old'=>'cat', 'new'=>'chat'), array('old'=>'dog', 'new'=>'chien'));
foreach ($results as $row) {
    $fndrep[$row['old']] = $row['new'];
}

$pattern = '~(?=([A-Z]?)([a-z]?))\b(?i)(?:'
 // cyrillic => '~(?=([\x{0410}-\x{042F}]?)([\x{0430}-\x{044F}]?))\b(?i)(?:'
         . implode('|', array_keys($fndrep))
         . ')\b~';  // cyrillic => ')\b~u';

$newstring = preg_replace_callback($pattern, function ($m) use ($fndrep) {
    $lowm = $fndrep[strtolower($m[0])];
    if ($m[1])
        return ($m[2]) ? ucfirst($lowm) : strtoupper($lowm);
    else
        return $lowm;
}, $oldstring);

echo $newstring;