【问题标题】:Split an array by first letter containing html entity按包含 html 实体的第一个字母拆分数组
【发布时间】:2012-06-23 14:09:18
【问题描述】:

我有一个包含类似国家/地区的数组

array(249) {
  [0]=>
  array(4) {
    ["country_id"]=>
    string(1) "2"
    ["country_name_en"]=>
    string(19) "Åland Islands"
    ["country_alpha2"]=>
    string(2) "AX"
    ["country_alpha3"]=>
    string(3) "ALA"
  }
  etc.
}

我想用第一个字母分割它,所以我得到一个这样的数组

array(26) {
 'A' => array(10) {
    array(4) {
      ["country_id"]=>
      string(1) "2"
      ["country_name_en"]=>
      string(19) "Åland Islands"
      ["country_alpha2"]=>
      string(2) "AX"
      ["country_alpha3"]=>
      string(3) "ALA"
    }
    etc.
  }
  etc.
}

但问题是国家名称数组包含 html 实体作为第一个字符。

任何想法如何做到这一点?

提前致谢

彼得

【问题讨论】:

标签: php unicode utf-8 html-entities


【解决方案1】:

如果您希望将Åland Islands 归档在A 下,您需要比已经建议的html_entity_decode() 做更多的事情。

intl 包含Normalizer::normalize(),一个将Å 转换为Å 的函数。迷茫了吗?该 unicode 符号 (U+00C5) 在 UTF-8 中可以表示为 0xC385 (Composition) 和 0x41CC8A (Decomposition)。 0x41A0xCC8Å

因此,要正确归档您的岛屿,您需要执行以下操作:

$string = "Åland Islands";
$s = html_entity_decode($string, ENT_QUOTES, 'UTF-8');
$s = Normalizer::normalize($s, Normalizer::FORM_KD);
$s = mb_substr($s, 0, 1);

很可能,您的环境没有安装intl。如果是这种情况,您可以查看urlify(),这是一个将字符串简化为字母数字部分的函数。


以上你应该可以

  1. 循环原始数组
  2. 提取国家名称
  3. 清理国家名称并提取第一个字符
  4. 根据(3)的特征新建数组

注意:请注意,ArmeniaAustriaAustralia 国家/地区都将在 A 下归档。

【讨论】:

    【解决方案2】:

    遍历数组,使用html_entity_decode()解码html实体,然后使用mb_substr()拆分。

    foreach($array as $values) {
        $values['country_name_en'] = html_entity_decode($values['country_name_en']);
        $index = mb_substr($values['country_name_en'], 0, 1);
    
        $new_array[$index] = $values;
    }
    

    或者你可以使用jlcd建议的功能:

    function substr_unicode($str, $s, $l = null) {
        return join("", array_slice(
            preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l));
    }
    
    foreach($array as $values) {
        $values['country_name_en'] = html_entity_decode($values['country_name_en']);
        $index = substr_unicode($values['country_name_en'], 0, 1);
    
        $new_array[$index] = $values;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 2022-05-22
    • 2011-03-22
    • 1970-01-01
    • 2021-11-06
    相关资源
    最近更新 更多