简体   繁体   中英

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.

Take the last portion that does not contain / :

[^\/]+$

Demo


To match en / fa only:

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

Demo


Or a negative lookahead:

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

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM