[英]Regex and preg_match
I want to do a regex to match one of these strings: add
, delete
, edit
, read
. 我想做一个正则表达式来匹配以下字符串之一:
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: 我想让我的preg_match返回true,如果在我的字符串中它们是:
read
delete
add
edit
,
If they are other word or symbol, return false. 如果它们是其他单词或符号,则返回false。
Thanks you all. 谢谢大家
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"
}
}
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";
}
}
^(?:add|delete|read|edit)$
what are those hashes doing there btw ? 那些哈希在那里做什么?
demo here 在这里演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.