I'm trying to make a code that replace Arabic text to be supported in non Arabic supported programs
in that i will be need to reverse the text after replace but its shows some garbage stuff instead of the wanted result

Here Is The Code :

<?php
$string = "اهلا بك";
echo "$string <br>";
$Reversed = strrev($string);
echo "<br><b>After Reverse</b><br><br>";
echo "<br> $Reversed";
?>

Result :

اهلا بك

After Reverse


�٨� �؄ه٧

I need it to be the way it is but reversed ? not GARBAGE !!

有帮助吗?

解决方案

in order to make that strrev() support UTF-8 you need to use this Function

function utf8_strrev($str){
    preg_match_all('/./us', $str, $ar);
    return join('', array_reverse($ar[0]));
}

so we going to chage strrev() in our code to utf8_strev() :

$string = "اهلا بك";
echo "$string <br>";
$Reversed = utf8_strrev($string); // here we have changed it
echo "<br><b>After Reverse</b><br><br>";
echo "<br> $Reversed";

and the Result is :

اهلا بك

After Reverse


كب الها

其他提示

I have been using this one

taken from here http://php.net/manual/en/function.strrev.php#122953

function mb_strrev($str){
    $r = '';
    for ($i = mb_strlen($str); $i >= 0; $i--) {
        $r .= mb_substr($str, $i, 1);
    }

    return $r;
}

A more generic solution that handles all encodings, not only UTF-8:

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

    $length   = mb_strlen($string, $encoding);
    $reversed = '';

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

    return $reversed;
}

Thanks to Kevin van Zonneveld

$my_string = 'Очень длинный-длинный текст :)'; 

function user_reverse($str){    // name can be arbitrary
   
    $arr = mb_str_split($str);
            
    return join('',array_reverse($arr));
 }

 echo (user_reverse($my_string));  // ): тскет йыннилд-йыннилд ьнечО*
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top