0

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

stckvrw
  • 1,689
  • 18
  • 42

1 Answers1

1

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;
Lodder
  • 19,758
  • 10
  • 59
  • 100
  • @jumlancer - use a `foreach` loop as shown in my updated answer ;) – Lodder Jan 31 '14 at 11:07
  • Lodder - thanks so much! It works but once I've changed $row->oldword (and newword) to $row['oldword'], because it's not an ObjectList but an AssocList. There is no more the problem with cyrillic too, as you said – stckvrw Jan 31 '14 at 15:25