簡體   English   中英

如何刪除部分URL

[英]How to remove part of URL

假設我的網址是這樣的:

http://example.com/forum/index.php?topic=53.msg251#msg251

這一部分,我不知道如何刪除:

.msg251#msg251

雖然我確實嘗試過,但是我不確定自己是否接近正確執行。

 $linkraw = $items->link;
 $linkpattern = '/^.msg247#msg247/';
 $link = preg_match($linkpattern, $linkraw);

正確的做法是什么? 我在嘗試學習。

字符串函數strrpossubstr足以完成此任務。 而且肯定更快。

 $link = substr($linkraw, 0, strrpos($linkraw, "."))

說明:

  1. strrpos找到的位置. 從字符串的末尾開始。
  2. substr提取一個子字符串,直到位置. 在上一步中找到。

什么時候可行?

適用於http://example.com/forum/index.php?topic=53.msg251#msg251
適用於http://example.com/forum/index.php?topic=53.new#new
不在 http://example.com/forum/index.php?topic=53.msg251#msg251.new#new

如果要刪除,請使用preg_replace

$link = preg_replace('/\..*?$/', '', $linkraw);

使用http_build_url函數非常簡單(需要PECL pecl_http> = 0.21.0)。

<?php
    $url = 'http://example/forum/index.php?topic=53.msg251#msg251';
    echo http_build_url($url, null, HTTP_URL_STRIP_FRAGMENT);
?>

“ preg_match()返回模式匹配的次數。這將是0次(不匹配)或1次,因為preg_match()將在第一個匹配之后停止搜索。相反,preg_match_all()將繼續直到到達結尾如果發生錯誤,則preg_match()返回FALSE。”

鏈接

Preg_Match僅檢查模式是否存在於字符串中。 它不會刪除任何東西。

您可以使用str_replace()替換該部分

$link = str_replace(".msg251#msg251", "", $linkraw);

暫無
暫無

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

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