Tony Stark Tony Stark - 3 months ago 21
PHP Question

PHP - Find occurence in array and then place the replaced part at the start

Here is my code:

function TranslatedTitle($Title) {
ConnectWithMySQLDatabase();

$v = mysql_query("SELECT * FROM `ProductTranslations`");
while($vrowis = mysql_fetch_array($v)){

$English[] = $vrowis['English'];
$Bulgarian[] = $vrowis['Bulgarian'];
}

$TranslatedTitle = str_replace($English, $Bulgarian, $Title);

return $TranslatedTitle;
}


I am using this code to fetch data from MySQL table and then search for certain phrase in English and then replace it with the phrase setted to replace the English one with the Bulgarian one.

Example:

I have very big blue eyes.

Will be translated to:
I have very големи сини eyes
. It takes the phrase
big blue
and replace it with
големи сини
at the position where it can be found.

In other words how can i make the replaced part to be moved in the beginning of the string giving final result by my example as
големи сини I have very eyes
.

The sentence in the example have no meaning but i have created it as an example.

Answer

I would try looping through the $English array and when finding the matching word move it to the beginning, then translating... something like:

foreach($English as $word){
   $pos = strpos($Title, $word);

   if ($pos !== false) {
      //english word found
      $Title = $word . str_replace($English, '', $Title);
      break;
   }
}

Then

$TranslatedTitle = str_replace($English, $Bulgarian, $Title);