簡體   English   中英

如何從php中的URL獲取單詞?

[英]how to fetch word from url in php?

網址字串

http://localhost/magento_prac/index.php/electronics/computers.html
http://localhost/magento_prac/index.php/electronics/cell-phones.html

我想從網址獲取“計算機”。 前“計算機”,“手機”

嘗試類似

$category = preg_replace('/^.*\/(.*)\.html$/', '$1', $url);

正則表達式匹配從字符串開頭( ^ )到最后一個/( \\/ )的所有內容( .* )。 然后,它再次匹配所有內容( .* ),但結尾處的.html除外,並期望字符串在該字符串( $ )之后結束。

第二個.*周圍的方括號允許您將替換中匹配的那部分稱為$1

您可以將URL轉換為attay並使用array_pop()獲取最后一個元素:

$urlArray = explode('/', $url);
$word = substr(array_pop($urlArray),0,-5);

試試這個代碼:

//get the url
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

//seperate the segments using explode()
$segments = explode('/', $url);

//and get the last segment
$last = explode('.', end($segments));

//use the last segment
echo $last[0];

為了方便起見,這是另一個選擇:

$url = 'http://localhost/magento_prac/index.php/electronics/computers.html';
$category = pathinfo($url)['filename']; // "computers"

上面的示例假定應用程序至少在PHP 5.4上運行以使用數組取消引用。

pathinfo返回有關文件路徑的信息。

'dirname' => string 'http://localhost/magento_prac/index.php/electronics'
'basename' => string 'computers.html'
'extension' => string 'html'
'filename' => string 'computers'

暫無
暫無

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

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