识别并显示字符串中的禁止字符

发布于 2024-12-04 02:44:19 字数 435 浏览 1 评论 0原文

我试图找到在 PHP 中执行此操作的最佳方法:

我必须分析字符串。

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

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

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

分析后,我想打印:

Character COMMA is forbidden
Character PERCENTAGE is forbidden

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

你们中有人遇到过这样的问题吗?

我尝试过 REGEX 和 STRPOS,但没有显着的结果。

I'm trying to find the best way to do this in PHP :

I have to analyse a string.

Some characters are forbidden (i.e. : comma, semicomma, space, percentage... but it can be any character I want, not only punctuation signs !)

I would like to print a line FOR EACH forbidden character in the string :

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

After analyse, I want to print :

Character COMMA is forbidden
Character PERCENTAGE is forbidden

The summum could be to have only one line for multiple errors with the same character.

Did some of you experienced such a problem ?

I've tried REGEX and STRPOS, but without significant result.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱的故事 2024-12-11 02:44:19

使用 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”等单词,您将必须为其创建一个散列。

Use 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";
}

The output of the above is:

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

The preg_match_all will return all instances of the $forbidden regex. You can adjust the characters in that regex as you see fit. The array_unique will eliminate duplicates.

Finally, I am just outputting the characters themselves in the output. If you want words like "COMMA", "PERCENTAGE", etc..., you will have to create a hash for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文