Question

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.

Was it helpful?

Solution 2

Try this one:

^(?:(?:add|delete|read|edit)|,)$

regex101 demo

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";
    }
}

ideone demo

OTHER TIPS

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"
  }
}
^(?:add|delete|read|edit)$

what are those hashes doing there btw ?

demo here

http://regex101.com/r/zX2yU8

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top