Regex - Greek Characters in URL

一个人想着一个人 提交于 2019-12-23 16:30:22

问题


I have a custom router that uses regex.

The problem is that I cannot parse Greek characters.


Here are some lines from index.php:

$router->get('/theatre/plays', 'TheatreController', 'showPlays');
$router->get('/theatre/interviews', 'TheatreController', 'showInterviews');
$router->get('/theatre/[-\w\d\!\.]+', 'TheatreController', 'single_post');

Here are some lines from Router.php:

$found = 0;
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); //get the url

////// Bla Bla Bla /////////

if ( $found = preg_match("#^$value$#", $path) )
{
    //Do stuff
}

Now, when I try a url like http://kourtis.app/theatre/α (notice the last character is a Greek 'alpha') then it is somehow interpreted to http://kourtis.app/theatre/%CE%B1

I can see this when I var_dump($path) or when I copy-paste the url.


I guess it has something to do with encoding but everything (I can think of) is in utf-8 format.

Any ideas?

--------------------------------

UPDATE: After the suggestions in the comments, the following works for only with some Greek characters: /theatre/[α-ωΑ-Ω-\w\d\!\.]+ and use urldecode to decode the percent-encoding of the $path variable.

Some characters that produce an error are: κ π ρ χ.

The question now is ... why?? (BTW, this works for many chars /theatre/.+)


回答1:


You can use

$router->get('/theatre/[^/]+', 'TheatreController', 'single_post');

as [^/]+ will match one or more characters other than / since [^...] is a negated character class that matches any char but the one(s) defined in the class.

Note you do not have to use \d if you used \w (\w already matches digits).

Also, you did not match diacritics with your regex. If you need to match diacritics, add \p{M} to the regex: '/theatre/[-\w\p{M}!.]+'.

Note that to allow \w to match Unicode letters/digits, you need to pass /u modifier to the regex: $found = preg_match("#^$value$#u", $path). This will both treat input strings as Unicode strings, and make shorthand patterns like \w Unicode aware.

Another thing: you need not escape . inside a character class.

Pattern details:

  • #...# - regex delimiters
  • ^ - start of string
  • $value - the $value variable contents (since double quoted strings in PHP allow interpolation)
  • $ - end of string
  • #u - the modifier enabling PCRE_UTF and PCRE_UCP options. See more info about them here


来源:https://stackoverflow.com/questions/39076407/regex-greek-characters-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!