0

I tried suggested solutions from other regex questions with preg_match but to no avail.

$match = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)\$/';
$filteredArray = array_filter($wordArray, function($x){
return !preg_match($match,$x);
});

It works when I include the string literal but I'd like to use a variable so I can add more words. This version works:

$filteredArray = array_filter($wordArray, function($x){
return !preg_match("/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)$/",$x);
});

I appreciate any help!

2
  • Not sure if the solution but try to use double quoutes as in working example. Commented Dec 28, 2011 at 21:03
  • Ups, just got it. Its because of variable scope. Posting as answer Commented Dec 28, 2011 at 21:04

3 Answers 3

2

This doesnt work beause of the variable scope. You can't access variable $match from that function.

Solution in to use globals. They are accessible from everywhere.

$GLOBALS['word_regex'] = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)\$/';
$filteredArray = array_filter($wordArray, function($x){
return !preg_match($GLOBALS['word_regex'],$x);
});

That should work

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much Kristian. Sorry to be a pain, but Amadan pointed out a much better option for adding new words which would be to use in_array. I tried this but haven't gotten it to work. Could you please point out what I'm doing wrong here: $forbiddenWordsArray = array("a","an","the","this","at","in","or","of","is","for","to","its","as","by"); $filteredArray = array_filter($wordArray, function($x){ return !in_array($x,$forbiddenWordsArray); });
NVM! It was the same variable scope problem.
Replace all instances of $forbiddenWordsArray with $GLOBALS['$forbiddenWordsArray'] and you should be done :) And you would be pain in the ass, then ei wouldn't be in here:) NP
Globals are unnecessary; use a closure. Add a use ($match) to the anonymous function to access the variable (though the variable holding the pattern should be renamed; $match is usually used for the result of group capturing).
2

Why regexp? Why not !in_array($x, $forbiddenWordsArray)? This way, easier to dynamically manage elements.

Comments

2

Anonymous functions don't automatically capture variables from the enclosing scope. You'll need to explicitly do this using a use declaration:

$shortWords = '/^(.|a|an|and|the|this|at|in|or|of|is|for|to|its|as|by)\$/';
$filteredArray = array_filter($wordArray, 
                              function($x) use ($shortWords) {
                                  return !preg_match($shortWords,$x);
                              });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.