gpt4 book ai didi

php - str_replace() 与 foreach、大写和精确单词匹配

转载 作者:可可西里 更新时间:2023-10-31 23:31:18 24 4
gpt4 key购买 nike

我的代码是:

$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"列中的单词。但是有两个问题。首先,如果找到的单词和替换的单词都具有相同的大小写(大写或小写),它会起作用,但我需要它在任何情况下都能正常工作,即数据库只有小写字母,但如果前端的查找单词有大写字母, 被替换的单词也必须大写。其次,我需要精确的单词匹配。提前致谢!

最佳答案

尝试这样的事情:

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

关于php - str_replace() 与 foreach、大写和精确单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21502612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com