开发者

Identify and show what forbidden characters are in a string

开发者 https://www.devze.com 2023-04-04 03:06 出处:网络
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

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 :

$st开发者_如何学运维ring = "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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消