Php 我怎样才能得到字符串的最后一段?

Php 我怎样才能得到字符串的最后一段?,php,regex,Php,Regex,夏季: $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/78

夏季:

$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
我需要获取此字符串的最后一部分:

$str = 'http://localhost:8000/news/786425/fa';
//                              last part ^^
我该怎么做


说明:

$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
我试图在URL的末尾添加一种语言(如果它不存在),或者用
en
(如果已经存在一种语言)替换它。我的网站只支持两种语言:
en
fa
。因此,只需将
en
fa
检测为语言。换句话说,它们是允许使用的语言,其他任何东西都可以被视为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


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

以不包含
/
的最后一部分为例:

[^\/]+$


要仅匹配
en
/
fa

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


或者是消极的前瞻:

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

注意到,我可以
分解()
每个
/
的字符串,然后使用数组的最后一项,但我喜欢使用正则表达式。是的,它几乎可以工作。。但正如我在问题中提到的,我需要在模式中同时使用
en
fa
。类似于这样的:
\/(?:en | fa)$
upvote(因为这个解决方案回答了我问题的一部分)。