【问题标题】:Identify and show what forbidden characters are in a string识别并显示字符串中的禁用字符
【发布时间】:2011-09-12 17:01:22
【问题描述】:

我正在尝试在 PHP 中找到最好的方法:

我必须分析一个字符串。

禁止使用某些字符(即:逗号、半逗号、空格、百分比......但它可以是我想要的任何字符,不仅仅是标点符号!)

我想在字符串中为每个禁止字符打印一行:

$string = "My taylor, is rich%";

分析后,我想打印:

Character COMMA is forbidden
Character PERCENTAGE is forbidden

对于相同字符的多个错误,总和可能只有一行。

你们中的一些人是否遇到过这样的问题?

我尝试了 REGEX 和 STRPOS,但没有明显的效果。

【问题讨论】:

  • 谢谢meagar,我忘记了问题中的“代码”标签。

标签: php regex string character identify


【解决方案1】:

使用preg_match_all

$forbidden = "/[,;%]/";
$string = "My taylor, is rich%; he is breaking my bank, natch";
$matches = null;
preg_match_all($forbidden, $string, $matches);
$chars = $matches ? array_unique($matches[0]) : array();

foreach ($chars as $char) {
    echo "Character {$char} is forbidden\n";
}

上面的输出是:

Character , is forbidden
Character % is forbidden
Character ; is forbidden

preg_match_all 将返回 $forbidden 正则表达式的所有实例。您可以根据需要调整该正则表达式中的字符。 array_unique 将消除重复。

最后,我只是在输出中输出字符本身。如果您想要“COMMA”、“PERCENTAGE”等词,则必须为此创建一个哈希。

【讨论】:

  • 太好了,正是我需要的!非常感谢你,本。
猜你喜欢
  • 2019-03-28
  • 2016-10-24
  • 2021-11-12
  • 1970-01-01
  • 2014-03-25
  • 2016-07-25
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
相关资源
最近更新 更多