In this case you don't need a regex, you can use in_array
:
$arr = array('true', 'false', 'TRUE', 'FALSE');
$result = (in_array($str, $arr, true)) ? $str : '';
Question
I need to allow only a specific word per time per string, but exists multiple valid words.
Using the below regex i am not getting the expected result:
preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'false'); // Returns an empty string, but i expect 'false'
preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'test') // Returns 'test', but i expect an empty string
Someone knows what's wrong?
EDIT 1
An example for a long input:
preg_replace('/\b^(true|false|TRUE|FALSE)\b/', '', 'This regex allow only boolean, such as true, false, TRUE and FALSE');
It prints:
// This regex allow only boolean, such true, false, TRUE and FALSE
But i expect an empty string, because only a sigle word should be a valid match
Solution 3
In this case you don't need a regex, you can use in_array
:
$arr = array('true', 'false', 'TRUE', 'FALSE');
$result = (in_array($str, $arr, true)) ? $str : '';
OTHER TIPS
Your regex is wrong for what you're trying to do. You will need negative lookahead.
Try this code:
$re = '/\b(?!(?:true|false|TRUE|FALSE))\w+\b/';
$str = 'I need true to allow only false specific FALSE words in a TRUE string';
$repl = preg_replace($re, "", $str);
//=> true false FALSE TRUE
Not sure I well understand your needs, but is that OK for you:
if (preg_match('/^(true|false|TRUE|FALSE)$/', $string, $match)) {
echo "Found : ",$m[1],"\n";
} else {
echo "Not found\n";
}
Is this what you want?
(?=.)(true|false|TRUE|FALSE|\s*)(?!.)
$regex = '/(?=.)(true|false|TRUE|FALSE|\\s{0,})(?!.)/';
$testString = ''; // Fill this in
preg_match($regex, $testString, $matches);
// the $matches variable contains the list of matches