簡體   English   中英

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

[英]How can I get last segment of the string?

綜述:

我需要得到這個字符串的最后一部分:

$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

是我到目前為止所嘗試的內容。

取最后一部分不包含/

[^\/]+$

演示


僅匹配en / fa

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

演示


或否定前瞻:

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM