Php – Extract characters occurring before one of several forbidden characters


I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.

As soon as a blacklisted character is encountered, the string before that point should be returned.

For instance, if I have an array:

$chars = array("a", "b", "c");

How would I go through the following string…

log dog hat bat

…and end up with:

log dog h

Best Solution

The strcspn function is what you are looking for.


$mask = "abc";

$string = "log dog hat bat";

$result = substr($string,0,strcspn($string,$mask));