1
$fileSyntax = strtolower(preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($fileSyntax, ENT_QUOTES, 'UTF-8'))); // remove foreign character accents
$fileSyntax = preg_replace("/[^a-zA-Z0-9\s]/", "", $fileSyntax); // remove anything that's not alphanumeric, or a space
$fileSyntax = preg_replace("/\s+/", "-", $fileSyntax); // replace space with hyphen     
$fileSyntax = trim($fileSyntax, "-"); // removes prefixing and trailing hyphen

The above code will produce the following:

Pokémon = pokemon
YO MAN! = yo-man

I want to rewrite this for efficiency and convert it into a function soon thereafter.

How can I utilize more than one preg_replace() so this will not be a multi-line code?

4

6 に答える 6

1

ご存知のように、この行:

$fileSyntax = preg_replace("/[^a-zA-Z0-9\s]/", "", $fileSyntax);

ハイフンを含める必要があります。そうしないと、ユーザーが入力できice-skateなくなり、たとえば、iceskate になります。

$fileSyntax = preg_replace("/[^a-zA-Z0-9\s-]/", "", $fileSyntax);

ハイフンは単語で使用できるため、スペースは実際にはアンダースコアに置き換える必要があります (私の意見では)。

また、関数に対してこれを行うこともできます:

function replace_chars($fileSyntax){
    return strtolower(
        preg_replace(
            array(
                "/&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);/i",
                "/[^a-zA-Z0-9\s-]/i",
                "/\s+/"
            ),
            array(
                "$1", // remove foreign character accents
                "", // remove anything that's not alphanumeric, hyphen or a space
                "_" // replace space with underscore 
            ), htmlentities($fileSyntax, ENT_QUOTES, 'UTF-8')
        )
    );
}

技術的にはすべて 1 行のコードであり、読みやすく、何が起こっているのかを理解しやすいように間隔を空けて配置されています。あなたはreplace_chars("TeRríbLé(!) STRinG :)");それを返す必要がある行くことによってそれを呼び出すでしょうterrible_string

于 2012-05-13T09:31:11.967 に答える
0

preg_replacesをsubjectパラメーターとして配置できます。これにより、replaceが返すものが、anothereplaceなどのサブジェクトになります。

于 2012-05-04T08:04:39.297 に答える
0

この関数は、問題の一部を解決できると思います 。http : //www.php.net/manual/en/function.iconv.php特殊文字を置き換えることにより、文字列を別の文字セットに変換します。

于 2012-05-04T08:05:07.707 に答える
0

複数行のコードや関数には何も問題はありません。読みやすく、長いコード行と同じように機能します。これは、何かがシリアルである場合、シリアルを維持し、実行にかかる時間が同じになるためです。プロセスを高速化したい場合は、同じ黒板文字列で並列スレッドを機能させることを試みることができますが、それはかなり複雑になります(すべての競合の問題を解決する必要があります)。

于 2012-05-04T08:10:21.060 に答える