PHP 替换除 [a-zA-Z0-9-] 以外的所有字符


PHP Replace all characters other than [a-zA-Z0-9-]

我想用空格替换[a-zA-Z0-9'-]以外的字符串中的所有字符。

找到了这篇文章,无论我调整 REGEX 多少次,我都无法让它"不匹配 [a-zA-Z0-9-],只匹配和替换其他字符"。

目前,我有以下内容:

$original_name = trim(' How to get file creation & modification date/times in Python?  ');
$replace_strange_characters = preg_replace("/^((?!([a-zA-Z0-9'-]+)*))$/", " ", $original_name);
// Returns: How to get file creation & modification date/times in Python?
echo $replace_strange_characters;

我希望它用空格"替换所有奇怪的字符,从而返回:

How to get file creation   modification date times in Python?

我真的在为这些"不匹配"的情况而苦苦挣扎。

这是我到目前为止的代码:http://tehplayground.com/#2NFzGbG7B

你可以

试试这个(你提到你想保持破折号)

$original_name = trim(' How to get file creation & modification date/times in Python?  ');
$replace_strange_characters = preg_replace('/[^'da-z-]/i', ' ', $original_name);
echo $replace_strange_characters;

演示。

这个正则表达式不会这样做吗?

[^a-zA-Z0-9'-]

哦,顺便说一句,你为什么要这样做?

试试这个

$replace_strange_characters = preg_replace("([^a-zA-Z0-9'-'?])", " ", $original_name);

前面的答案去除了?