php 字符串过滤特殊字符

* mb_ord.php

<?php

class Str {
    public static function filter(string $s, callable $f=null, string $encoding = 'UTF-8') {
        $enc = mb_detect_encoding($s);
        if ($enc !== $encoding) {
            throw new RuntimeException("invalid encoding, $encoding expected");
        }

        $a = preg_split('//u', $s, null, PREG_SPLIT_NO_EMPTY);

        $b = array_map(function($chr) use ($enc) {
            return mb_ord($chr, $enc);
        }, $a);
        $a = null;

        if (is_null($f)) {
            $f = function($c) {
                return $c < 256 || (0x4e00 <= $c && $c <= 0x9fa5);
            };
        }
        $b = array_filter($b, $f);

        $a = array_map(function($c) {
            return mb_chr($c);
        }, $b);
        return implode('', $a);
    }
}

* test:

$s = " ✧\\ ٩( ‘㉨’ )و //✧o(๑◕ ㉨ ◕๑)ブ~ヘー﹣✿挥爪~⊂(˃̶͈̀㉨ ˂̶͈́ ⊂ )))≡=─ ";
echo Str::filter($s).PHP_EOL;

$ php mb_ord.php 
 \ (  ) /o(  )~挥爪~(   )))=

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/84784721