简体   繁体   English

如何获取字符串的最后一段?

[英]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) . 我试图在URL的末尾添加一种语言(如果它不存在)或者用en替换它(如果一种语言已经存在) My website supports only two languages: en , fa . 我的网站只支持两种语言: enfa So just en and fa should be detected as languages. 因此, enfa应该被检测为语言。 In other word, they are allowed languages, anything else would considered as a URL's parameter. 换句话说,它们是允许的语言,其他任何东西都被视为URL的参数。


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

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

Demo 演示


Or a negative lookahead: 或否定前瞻:

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

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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