Search code examples
phparraysarray-filter

Remove element from array if contains some string/symbol


I have an array containing some words and I want to remove the words that contain either a . (fullstop) or ; (semicolon) or some other symbols. I have read the solution on [ Remove item from array if item value contains searched string character ] but this doesn't seem to answer my problem.

What can I add to this code to remove also the words containing the other symbols other than semicolon?

function myFilter($string) {
  return strpos($string, ';') === false;
}

$newArray = array_filter($array, 'myFilter');

Thanks


Solution

  • Use preg_match function:

    function myFilter($string) {
        return !preg_match("/[,.]/", $string);
    }
    

    [,.] - character class which can be extended with any other symbols