转义 "str_replace" PHP 函数中的特殊字符

Escaping special characters in "str_replace" PHP function

我有以下功能 str_replace:

function url_seo($text)
{
    $match    = array(']','\',';',"'",',','.','/','~','`','=');
    $replace  = array('-','','','','','','','','','');
    $text     = str_replace($match, $replace, $text);
    return $text;
}

我是否应该像这样在 $match 变量中的所有字符前放置一个 \

$match = array('\]','\','\;',"\'",'\,','\.','\/','\~','\`','\=');

还是不需要?

根据 str_replace PHP reference

search
The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.

因此,这不是正则表达式,除了必须始终转义的 escape sequences 之外,您不必转义任何字符。

\" Print the next character as a double quote, not a string closer
\' Print the next character as a single quote, not a string closer
\n Print a new line character
\t Print a tab character
\r Print a carriage return (not used very often)
$ Print the next character as a dollar, not as part of a variable
\ Print the next character as a backslash, not an escape character

因此,您的字符串数组中只有 \ 应该被转义。

根据字符串限定符的不同,您可能还需要转义 '",但您可以像之前那样交替使用它们:'"'"'" 是避免过度转义的好方法。