stack stack - 1 month ago 7
PHP Question

How can I get last segment of the string?

Summery:

I need to get last part of this string:

$str = 'http://localhost:8000/news/786425/fa';
// last part ^^


How can I do that?




Explanation:

I'm trying to either add a language in the end of URL (if it isn't exist) or replace it with
en
(if a language already exists). My website supports only two languages:
en
,
fa
. So just
en
and
fa
should be detected as languages. In other word, they are allowed languages, anything else would considered as a URL's parameter.




Examples:

$str = 'http://localhost:8000/news/786425/fa';
// expected output: http://localhost:8000/news/786425/en

$str = 'http://localhost:8000/news/786425';
// expected output: http://localhost:8000/news/786425/en

$str = 'http://localhost:8000/news/786425/pg'; // pg is not defined as a language
// expected output: http://localhost:8000/news/786425/pg/en


$str = 'http://localhost:8000/news/786425/en';
// expected output: http://localhost:8000/news/786425/en





Here is what I've tried so far.

Answer

Take the last portion that does not contain /:

[^\/]+$

Demo


To match en/fa only:

(?=(?:en|fa)$)[^\/]+$

Demo


Or a negative lookahead:

(?!\/)(?:en|fa)$

Demo