且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP 替换特殊字符,如 à->a、è->e

更新时间:2021-11-04 08:25:01

有一个更简单的方法,使用 iconv - 从用户注释来看,这似乎是你想要做的: 字符音译

There's a much easier way to do this, using iconv - from the user notes, this seems to be what you want to do: characters transliteration

// PHP.net User notes
<?php
    $string = "ʿABBĀSĀBĀD";

    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $string);
    // output: [nothing, and you get a notice]

    echo iconv('UTF-8', 'ISO-8859-1//IGNORE', $string);
    // output: ABBSBD

    echo iconv('UTF-8', 'ISO-8859-1//TRANSLIT//IGNORE', $string);
    // output: ABBASABAD
    // Yay! That's what I wanted!
?>

非常认真地处理您的字符编码,以便在流程的所有阶段保持相同的编码 - 前端、表单提交、源文件的编码.PHP 和表单中的默认编码是 ISO-8859-1,在 PHP 5.4 之前它更改为 UTF8(终于!).

Be very conscientious with your character encodings, so you are keeping the same encoding at all stages in the process - front end, form submission, encoding of the source files. Default encoding in PHP and in forms is ISO-8859-1, before PHP 5.4 where it changed to be UTF8 (finally!).

有几个函数可以让您发挥创意.第一个来自 CakePHP 的 inflector 类,叫做 slug:

There's a couple of functions you can play around with for ideas. First is from CakePHP's inflector class, called slug:

public static function slug($string, $replacement = '_') {
    $quotedReplacement = preg_quote($replacement, '/');

    $merge = array(
        '/[^sp{Ll}p{Lm}p{Lo}p{Lt}p{Lu}p{Nd}]/mu' => ' ',
        '/\s+/' => $replacement,
        sprintf('/^[%s]+|[%s]+$/', $quotedReplacement, $quotedReplacement) => '',
    );

    $map = self::$_transliteration + $merge;
    return preg_replace(array_keys($map), array_values($map), $string);
}

这取决于 self::$_transliteration 数组,它与您在问题中所做的类似 - 您可以 查看 github 上的 inflector 源.

It depends on a self::$_transliteration array which is similar to what you were doing in your question - you can see the source for inflector on github.

另一个是我个人使用的一个函数,它来自这里.

Another is a function I use personally, which comes from here.

function slugify($text,$strict = false) {
    $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
    // replace non letter or digits by -
    $text = preg_replace('~[^\pLd.]+~u', '-', $text);

    // trim
    $text = trim($text, '-');
    setlocale(LC_CTYPE, 'en_GB.utf8');
    // transliterate
    if (function_exists('iconv')) {
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    }

    // lowercase
    $text = strtolower($text);
    // remove unwanted characters
    $text = preg_replace('~[^-w.]+~', '', $text);
    if (empty($text)) {
        return 'empty_$';
    }
    if ($strict) {
        $text = str_replace(".", "_", $text);
    }
    return $text;
}

这些函数的作用是从任意文本音译和创建slugs"输入,这是制作 Web 应用程序时工具箱中非常有用的东西.希望这会有所帮助!

What those functions do is transliterate and create 'slugs' from arbitrary text input, which is a very very useful thing to have in your toolchest when making web apps. Hope this helps!