2

Consider this,

$uri = '/post/search/foo';

$pattern = '~/post/search/[A-Za-z0-9_-]+(?=/|$)~i';

$matches = array();

preg_match($pattern, $uri, $matches);

print_r($matches); // Success

It works fine, since [A-Za-z0-9_-] belongs to foo. Since I'm writing a route plugin, I want this to be abble to match special chars as well.

I imagine a regex pattern to be like this:

[A-Z0-9!@#$%^&*()_+|\/?><~"№;:'*]+(?=/|$)

I've tried to escape each special character with a slash, and escape a whole pattern using preg_quote() with no luck - I always encounter compilation failures.

The question is, how a proper matching for A-Z0-9!@#$%^&*()_+|\/?><~"№;:'* should be done?

4

2 回答 2

2

在字符类中转义并不困难,只是^(仅在第一个位置),-(不是在第一个或最后一个位置),\并且[]是特殊字符,并且'作为字符串分隔符。并且附加了正则表达式分隔符。

~用作正则表达式分隔符,我认为这是您的字符类中的关键点,因为在使用preg_quote().

所以这应该有效

[A-Z0-9!@#$%^&*()_+|\/?><\~"№;:\'*]+(?=/|$)
于 2013-09-19T08:13:58.077 回答
2

您是否有理由不想只使用 ungreedy .

如:

'~/post/search/.+(?=/|$)~iU'
于 2013-09-19T08:05:20.000 回答