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

3

摘要:

我需要获取此字符串的最后一部分:

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

我该怎么做?


解释:

我正在尝试在URL的末尾添加语言(如果它不存在),或者用en替换它(如果语言已存在)。我的网站仅支持两种语言:enfa。因此只有enfa应被检测为语言。换句话说,它们是允许的语言,其他任何东西都将被视为URL的参数。


示例:

$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

这里是我到目前为止尝试过的。



请注意,我可以使用 explode() 函数将字符串按 / 分割成数组,然后使用数组的最后一个元素,但我更喜欢使用正则表达式来实现。 - stack
1个回答

4
取最后一部分不含 / 的内容:
[^\/]+$

演示


仅匹配en/fa

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

演示


或者使用负向先行断言:

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

演示


是的,它几乎可以工作了...但正如我在问题中提到的那样,我需要在模式中字面上使用enfa。就像这样:\/(?:en|fa)$ - stack
无论如何点赞(因为这个解决方案回答了我的问题的摘要部分)。 - stack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接