正则表达式和preg_match

时间:2014-03-20 09:53:46

标签: php regex preg-match pcre

我想使用正则表达式来匹配其中一个字符串:adddeleteeditread

我的正则表达式只能接受下面的字符串(而不是其他字):

    add

    delete 

    edit

    read

,

这是我当前的正则表达式,但它没有按预期工作:

#(add|delete|read|edit),#

修改

我希望我的preg_match返回true,如果在我的字符串中它们是:

read
delete
add
edit
,

如果它们是其他单词或符号,则返回false。

谢谢大家。

3 个答案:

答案 0 :(得分:3)

好像你做了一个小错误。该模式基本上应该工作。例如:

$str = <<<EOF
add, delete foo edit read bar add
hello world
EOF;

preg_match_all('#add|delete|read|edit|,#', $str, $matches);
var_dump($matches);

输出:

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

答案 1 :(得分:1)

试试这个:

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

regex101 demo

我使用了一个组来首先将选择限制为您的单个字符串,然后是锚点^$,以确保您正在测试它的字符串中没有其他内容。

$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

答案 2 :(得分:-1)

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

那些哈希在那里做什么btw?

演示

http://regex101.com/r/zX2yU8