如何从SQL中提取西里尔数据作为数组并使用str_replace()

时间:2014-01-31 10:46:47

标签: php sql arrays joomla cyrillic

我有代码:

mysql_connect('...');
mysql_select_db('...');
$result = mysql_query('SELECT `oldword`, `newword` FROM `#_words`');
$find = array();
$replace = array();
while ($row = mysql_fetch_assoc($result)) {
 $find[] = $row['oldword'];
 $replace[] = $row['newword'];
}
$oldstring = 'Some text';
$newstring = str_replace($find, $replace, $oldstring);
echo $newstring;

它运作良好,但有两个问题。首先,我需要将其转换为使用Joomla API,例如

$db = &JFactory::getDBO();
$db->setQuery('SELECT `oldword`, `newword` FROM `#_words`');
// and what is next, what about mysql_fetch_assoc ?

其次,如果oldword和newword是英语,那么它可以工作,但如果是西里尔语则不然。我该如何解决?我试过这个:

function fixEncoding($s, $encoding = 'UTF-8') {   
 $s = @iconv('UTF-16', $encoding . '//IGNORE', iconv($encoding, 'UTF-16//IGNORE', $s)); 
 return str_replace("\xEF\xBB\xBF", '', $s);
}
$find = fixEncoding($find);
$replace = fixEncoding($replace);

但此函数仅适用于单个字符串,不适用于数组

1 个答案:

答案 0 :(得分:1)

我必须对西里尔问题进行一些测试,但对于使用Joomla编码标准的数据库查询,它将如下所示:

$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select($db->quoteName(array('oldword', 'newword')))
      ->from($db->quoteName('#__words'));
$db->setQuery($query);

$results = $db->loadAssocList();
$find = array();
$replace = array();

foreach ( $results as $row ) {
    $find[] = $row->oldword;
    $replace[] = $row->newword;
}
$oldstring = 'Some text';
$newstring = str_replace($find, $replace, $oldstring);
echo $newstring;