2

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
mlh
  • 584
  • 2
  • 6
  • 18

1 Answers1

4

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.

Ben Lee
  • 52,489
  • 13
  • 125
  • 145