摘要:
我需要获取此字符串的最后一部分:
$str = 'http://localhost:8000/news/786425/fa';
// last part ^^
我该怎么做?
解释:
我正在尝试在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
这里是我到目前为止尝试过的。
explode()
函数将字符串按/
分割成数组,然后使用数组的最后一个元素,但我更喜欢使用正则表达式来实现。 - stack