php - How can I get last segment of the string?



I need to get last part of this string:

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

How can I do that?


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.


$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.




Take the last portion that does not contain/:



To matchen/fa only:



Or a negative lookahead:



People are also looking for solutions to the problem: php - how to replace ... between a word where one part is numeric the other is'int?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.