Search code examples
phpregexpreg-match

preg_match ( PHP ) : report the *FIRST* conflicting character & HALT the operation


Supposedly my string is:

$a = 'abc-def";

i only want a-z in my string.

but i want to let the user know what "bad" character makes their string "bad".

i can do this:

$conflict = preg_replace('/[a-zA-Z0-9 .]/', '', $a);
echo "the conflict was: $conflict";

but if my string is huge.. let's say a document filled with lots of text.. then this code above would go through the entire document and show all the conflicting characters.

i would like it to STOP after it finds only 1 conflicting character.

that way less CPU / memory / resources are used.

in other words.

$a = 'abc-,def";

in this example it should stop and indicate the conflict is "-"

rather than report the conflict is : "-,"

because soon as it sees "-" it should stop looking anymore.

the goal is to not use too many resources.

MORE INFO:

the idea is to read a string from left to right (i suppose) and soon as a character is detected that does not obey the law of a-z and 0-9.. the process is to be terminated and the string that has been found is to be reported


Solution

  • You can do the following:

    if (preg_match("/[^a-z0-9]/i", $a, $match)) :
      echo "Conflict was: $match[0]";
    

    Logic: Check for characters other than a-z0-9 and if there is a match print the response.