Reputation: 959
I want to do a regex to match one of these strings: add
, delete
, edit
, read
.
My regex has to only accept, the below strings (not others words):
add
delete
edit
read
,
Here's my current regex but it does not work as expected:
#(add|delete|read|edit),#
Edit
I want to my preg_match return true if in my string they are:
read
delete
add
edit
,
If they are other word or symbol, return false.
Thanks you all.
Upvotes: 0
Views: 181
Reputation: 71538
Try this one:
^(?:(?:add|delete|read|edit)|,)$
I used a group to limit the choices first to your individual strings, then the anchors ^
and $
to ensure there's nothing else in the string you're testing it against.
$words = array('add', 'delete', ',', 'reading', 'edit', 'read', 'gedit');
foreach ($words as $word) {
if (preg_match('#^(?:(?:add|delete|read|edit)|,)$#', $word)) {
echo "$word: Matched!\n";
} else {
echo "$word: Not matched!\n";
}
}
Upvotes: 1
Reputation: 157990
Seems you did a minor error. The pattern should basically work. Example:
$str = <<<EOF
add, delete foo edit read bar add
hello world
EOF;
preg_match_all('#add|delete|read|edit|,#', $str, $matches);
var_dump($matches);
Output:
array(1) {
[0] =>
array(6) {
[0] =>
string(3) "add"
[1] =>
string(1) ","
[2] =>
string(6) "delete"
[3] =>
string(4) "edit"
[4] =>
string(4) "read"
[5] =>
string(3) "add"
}
}
Upvotes: 3
Reputation: 11116
^(?:add|delete|read|edit)$
what are those hashes doing there btw ?
demo here
Upvotes: -1