如何在php范围内使用阿拉伯语字母()

时间:2016-03-30 16:40:24

标签: php range arabic

我想使用阿拉伯字母作为范围函数的输入:

foreach (range('ا', 'ی') as $letter) {
    echo $letter;
}

我找不到任何解决方案。

2 个答案:

答案 0 :(得分:0)

你不能使用range()来做这件事,因为它完全适用于ASCII字符,但是你可以做一些类似的事情" alphabet()"功能:

/*
 * By Darien Hager, Jan 2007... Use however you wish, but please
 * please give credit in source comments.
 *
 * Change "UTF-8" to whichever encoding you are expecting to use.
 */
function ords_to_unistr($ords, $encoding = 'UTF-8') {
    // Turns an array of ordinal values into a string of unicode characters
    $str = '';
    for ($i = 0; $i < count($ords); $i++) {
        // Pack this number into a 4-byte string
        // (Or multiple one-byte strings, depending on context.)
        $v = $ords[$i];
        $str .= pack("N",$v);
    }
    $str = mb_convert_encoding($str,$encoding,"UCS-4BE");
    return($str);
}

function unistr_to_ords($str, $encoding = 'UTF-8') {
    // Turns a string of unicode characters into an array of ordinal values,
    // Even if some of those characters are multibyte.
    $str = mb_convert_encoding($str,"UCS-4BE",$encoding);
    $ords = array();

    // Visit each unicode character
    for ($i = 0; $i < mb_strlen($str,"UCS-4BE"); $i++) {
        // Now we have 4 bytes. Find their total
        // numeric value.
        $s2 = mb_substr($str,$i,1,"UCS-4BE");
        $val = unpack("N",$s2);
        $ords[] = $val[1];
    }
    return($ords);
}

function alphabet($firstCharacter = 'A', $lastCharacter = 'Z') {
    $firstCharacterValue = unistr_to_ords($firstCharacter)[0];
    $lastCharacterValue = unistr_to_ords($lastCharacter)[0];

    if ($firstCharacterValue < $lastCharacterValue) {
        for ($character = $firstCharacterValue; $character <= $lastCharacterValue; ++$character) {
            yield ords_to_unistr(array($character));
        };
    } else {
        for ($character = $firstCharacterValue; $character >= $lastCharacterValue; --$character) {
            yield ords_to_unistr(array($character));
        };
    }
}

然后使用

foreach (alphabet('ا', 'ی') as $letter) {
    echo $letter;
}

Demo

答案 1 :(得分:0)

使用utf-8作为您的页面,数据库和服务器的主要编码(它允许您使用任何语言,而不仅仅是阿拉伯语!!例如,chinies) 如果您使用第三方服务器并且您无法更改服务器的配置,则可以始终在php中强制编码 header('Content-Type:text / html; charset = utf-8'); 如果您的数据库不支持UTF-8,您可以使用binnary insted of text