Question

I have the code:

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;

It works good but there are two problems. First I need to convert it for using Joomla API i.e. to something like

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

And secondly, if oldword and newword are english it works but if cyrillic it doesn't. How can I fix it? I have tried this:

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

but this function works with a single string only and doesn't work with array

Was it helpful?

Solution

I would have to do some testing regarding the cyrillic problem, but as for your database query using Joomla coding standards, it will look like this:

$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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top