汇总:
我需要得到这个字符串的最后一部分:
$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
以下是我迄今为止所做的尝试。
取不包含/
:的最后一部分
[^'/]+$
演示
仅匹配en
/fa
:
(?=(?:en|fa)$)[^'/]+$
演示
或者负面展望:
(?!'/)(?:en|fa)$
演示