简体   繁体   English

如何删除部分URL

[英]How to remove part of URL

Let's say my URL is this: 假设我的网址是这样的:

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

This part here, I can't figure out how to remove: 这一部分,我不知道如何删除:

.msg251#msg251

I did try though, I'm not sure if I am even close to doing it right. 虽然我确实尝试过,但是我不确定自己是否接近正确执行。

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

What is the correct way of doing this? 正确的做法是什么? I am trying to learn. 我在尝试学习。

String functions strrpos and substr are enough for this task. 字符串函数strrpossubstr足以完成此任务。 And its surely faster. 而且肯定更快。

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

Explanation: 说明:

  1. strrpos finds the position of . strrpos找到的位置. from the end of the string. 从字符串的末尾开始。
  2. substr extracts a sub string till the position of . substr提取一个子字符串,直到位置. found in previous step. 在上一步中找到。

When this will work? 什么时候可行?

Works on http://example.com/forum/index.php?topic=53.msg251#msg251 适用于http://example.com/forum/index.php?topic=53.msg251#msg251
Works on http://example.com/forum/index.php?topic=53.new#new 适用于http://example.com/forum/index.php?topic=53.new#new
But not on http://example.com/forum/index.php?topic=53.msg251#msg251.new#new 不在 http://example.com/forum/index.php?topic=53.msg251#msg251.new#new

如果要删除,请使用preg_replace

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

Quite simple using the http_build_url function (requires PECL pecl_http >= 0.21.0). 使用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() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred." “ preg_match()返回模式匹配的次数。这将是0次(不匹配)或1次,因为preg_match()将在第一个匹配之后停止搜索。相反,preg_match_all()将继续直到到达结尾如果发生错误,则preg_match()返回FALSE。”

link 链接

Preg_Match checks only if the pattern exists in the string. Preg_Match仅检查模式是否存在于字符串中。 It doesn't remove something. 它不会删除任何东西。

You can use str_replace() for replacing that part 您可以使用str_replace()替换该部分

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM