我在php中使用preg_match使用此正则表达式:
/^(node|widget|config)(\/[A-Z]+|)+([^\/]$)/i
RegExr如预期的那样,在这种情况下应匹配:
TYPE/custom/path/to
TYPE
但不是
TYPE/custom/path/to/
TYPE/
TYPE可以是节点,小部件或配置
但是在PHP中使用带有preg_match的表达式确实会匹配例如node
。一些提示如何更改我的正则表达式以起作用?
答案 0 :(得分:2)
我认为这是您想要的:
<?php
$pattern = '/^(node|widget|config)(\/[a-z]+)*$/i';
$test_paths = [
'node',
'widget',
'CONFIG',
'node/custom/path/to',
'node/',
'node/custom/path/to/'
];
foreach ($test_paths as $path) {
printf(
"- \"%s\" %s the regex.\n",
$path,
preg_match($pattern, $path)? 'matches' : 'does not match'
);
}
测试给出以下输出:
- "node" matches the regex.
- "widget" matches the regex.
- "CONFIG" matches the regex.
- "node/custom/path/to" matches the regex.
- "node/" does not match the regex.
- "node/custom/path/to/" does not match the regex.