Jump to content

[SOLVED] Change array values in a loop


msmarc

Recommended Posts

I was playing around with PHP and found a way to replace words in a string with other words using str_replace and arrays for the starting words and the replaced words.

 

I wanted an app where someone would enter Japanese characters into a text form, send it and my php would translate the character into english sounds such as "ma, ru, ka". I've done this but I want the returned string to have "-" in between each english sound so it would be "ma-ru-ka". I think in order to do this I would need to have the returned text be an array instead of a string. Is there anyway to find values through one array and replace them with values in another array based on key number and then put that data into a new array. This would be like using str_replace but having the values replace an array instead.

 

Heres the code I was using to just replace the string with the new text


$hiragana = $HTTP_POST_VARS['hiragana'];

$start = array  ( 'ま', 'る', 'こ', 'い' );
$end = array    ( 'ma', 'ru', 'ko', 'i' );

$hiragana = str_replace($start, $end, $hiragana);
echo $hiragana;

 

If I do this I don't know how to put "-" in between the different sounds because it all comes out of one string.

 

 

Link to comment
https://forums.phpfreaks.com/topic/151571-solved-change-array-values-in-a-loop/
Share on other sites

can't you just add a - after every english part and then trim off the starting and trailing - in the text, ex:

$start = array  ( 'ま', 'る', 'こ', 'い' );
$end = array    ( 'ma-', 'ru-', 'ko-', 'i-' );

$hiragana = str_replace($start, $end, $hiragana);
echo trim($hiragana, '-');

 

some examples pal.

<?php

$string="my username is redarrow";

echo str_replace(' ','-',$string);

?>

<?php echo "<br>";?>

<?php

$string="my username is redarrow";

$string=explode(" ",$string);

echo implode('-',$string);

?>

<?php echo "<br>";?>

<?php

$string="my username is redarrow";

$string=preg_replace("/ /","-",$string);

echo $string;

?>

I'd do it like this

 

$hiragana = $HTTP_POST_VARS['hiragana'];
$chars = array ( 'ま' => 'ma',
                 'る' => 'ru',
                 'こ' => 'ko',
                 'い' => 'i' );

foreach($chars as $find => $replace)
{
    $hiragana = str_replace($find, "$replace-", $hiragana);
}

echo $hiragana;

 

EDIT: Replace the &#12xxx; codes above with your actual characters. The forum is messing up the code

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.