I get part of the url after the slash

if (!preg_match('/^([0-9]+)/i', $url, $url_params)) { header("HTTP/1.0 404 Not Found"); } 

This option works if the URL has numeric values, for example, site.ru/123456/789

What to replace ([0-9]+) to get a part of the letter url, for example, site.ru/ qwer -dhfjf-dbjs?

You only need to get qwer

Thank!

  • If before the first space and only Latin, then \w+ . - entithat
  • `if (! preg_match ('/ ^ (\ w +) / i', $ url, $ url_params)) doesn’t work like this {` - MicroRu 9:51 pm
  • Replace ^ with \/ , then it will look for a match not from the beginning of the line, but from \/ - entithat

1 answer 1

Get part of the letter url, for example: site.ru/ qwer -dhfjf-dbjs

Find the slash / in the string, and get all subsequent alphabetic characters, before the first non-alphabetic character: '~/\pL+~' .

For the sake of fairness, it must be said that this template will work only for an incomplete url, and for example for such https://site.ru/qwer-dhfjf-dbjs the substring site will be found.

If you need to take into account in the protocol protocol, then the template can be written as follows: '~(?://)?[^/]+/\K\pL+~'

 $url = 'https://site.ru/qwer-dhfjf-dbjs'; if (! preg_match('~(?://)?[^/]+/\K\pL+~', $url)) { header("HTTP/1.0 404 Not Found"); }