【问题标题】:str_replace() with foreach, uppercase and exact word matchingstr_replace() 与 foreach、大写和精确单词匹配
【发布时间】:2014-02-25 11:28:49
【问题描述】:

我的代码是:

$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;

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

【问题讨论】:

  • 那就试试str_ireplace
  • 你所说的“前端的查找词[有]大写”到底是什么意思?如果只有单词的第一个字母是大写的,替换字符串的第一个字母是否也是大写的?还是单词总是完全大写或小写?
  • 所有可能的情况都是最好的解决方案,即替换的单词必须始终与找到的单词相同(旧 - 新,旧 - 新,旧 - 新)但在数据库中它们必须在仅小写

标签: php regex arrays string str-replace


【解决方案1】:

试试这样的:

$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;  

【讨论】:

  • 谢谢!是的,但只有英语。我需要西里尔字母,抱歉我没有在帖子中提到它
  • @jumlancer:您只需要将范围A-Z 替换为西里尔大写字母,将a-z 替换为小写即可。
猜你喜欢
  • 2012-03-29
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2019-08-09
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多