phparraysreplaceright-to-lefthebrew

After declaring an array of translations including Hebrew characters, str_replace() does not replace substrings as expected


I have an array with Hebrew words that I need to find in a string and replace. The translation array is defined as key-value pairs.

In English, this works.

   function replace_twophrase_words($string) {

    $string = strtolower($string);

    $replacements = array (
        'movers'                =>  'Moving Services',
        'home-moving'           =>  'Home Moving',
        'commercial-moving'     =>  'office-moving',
    );


    $string = str_replace($replacements, array_keys($replacements), $string);
}

Hebrew array (asked in comments):

$replacements = array (
    'עיצוב-פנים'            =>  'עיצוב פנים',
    'עיצוב-פנים'            =>  'מעצבת פנים',
    'עיצוב-פנים'            =>  'עיצוב משרדים',
);

But... it seems that this doesn't work in Hebrew at all. Can anyone explain what's gone wrong?


Solution

  • You need to use mb_ereg_replace:

    setlocale( LC_CTYPE, 'en_US.UTF-8' );
    header( 'Content-Type: text/plain; charset=utf-8' );
    echo mb_ereg_replace( 'עיצוב-פנים', 'עיצוב פנים', 'Hebrew string is here: עיצוב-פנים ; and back to Latin.' );
    

    This is because Hebrew letters are composed of multiple bytes and str_reaplce and preg_replace (by default) do not understand these.