RonZ
RonZ

Reputation: 853

php | reverse hebrew string, but without reverse english letters

I'd like to print a string on image with imagettftext function, but I've got one problem - the text is hebrew and shown as reverse.

I tried using strrev function (and others) to reverse the string, and it works - but if its has english letters in it - I get reversed english letters as well.

There is a way to reverse the hebrew letters, but saving the english words as they are?

Upvotes: 3

Views: 1344

Answers (1)

Megas
Megas

Reputation: 81

I wrote following solution:

function reverseHebrew($text)
{
    $words = array_reverse(explode(' ', $text));
    foreach ($words as $index => $word) {
        if (isHebrew($word)) {
            $words[$index] = mbStrRev($word);
        }
    }
    return join(' ', $words);
}

function isHebrew($text)
{
    for ($i = 0, $cnt = strlen($text); $i < $cnt; ++$i) {
        if (ord($text[$i]) > 127) {
            return true;
        }
    }
    return false;
}

function mbStrRev($string, $encoding = null) 
{
    if ($encoding === null) {
        $encoding = mb_detect_encoding($string);
    }

    $length   = mb_strlen($string, $encoding);
    $reversed = '';
    while ($length-- > 0) {
        $reversed .= mb_substr($string, $length, 1, $encoding);
    }

    return $reversed;
}

Usage:

echo reverseHebrew("שלום user");

Upvotes: 5

Related Questions