php - 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 withen
(if a language already exists). My website supports only two languages:en
,fa
. So justen
andfa
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
Solution:
Take the last portion that does not contain
/
:Demo
To match
en
/fa
only:Demo
Or a negative lookahead:
Demo