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

时间:2016-11-01 05:28:05

标签: php regex

综述

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

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

我该怎么做?

解释

我尝试在网址的末尾添加语言(如果它不存在)或将其替换为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

Here是我迄今为止所尝试过的。

1 个答案:

答案 0 :(得分:4)

取最后一部分不包含$arr[1]

/

Demo

仅匹配[^\/]+$ / en

fa

Demo

或否定前瞻:

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

Demo

相关问题