仅删除 php 中的特殊字符和数字

Remove special character and number only in php

我们如何在不删除字符串中的空格的情况下删除数字和特殊字符?

例如:

$input = "Random string with random 98 and %$% output"; 

$filtered_input = preg_replace("/[^a-zA-Z\s]/", "", $input);

我试过上面的代码,但它不起作用。我也尝试阅读 php 手册,但我不太理解其中的内容。我在网上找到的所有示例都从字符串中删除了空格。任何人都可以告诉我如何完成或为我推荐一些好的读物

非常感谢。

您可以使用

$input = "Random string with random 98 and %$% output"; 
$filtered_input = trim(preg_replace("/\s*(?:[\d_]|[^\w\s])+/", "", $input));
echo $filtered_input;

输出:

Random string with random and output

参见regex demo and the PHP demo

详情:

  • \s* - 0+ 个空格(在您需要删除的值之前)
  • (?:[\d_]|[^\w\s])+ - 数字或下划线或除单词和空格以外的任何字符出现一次或多次。

trim 函数会删除任何生成的前导空格(如果有的话)。