nowayyy
nowayyy

Reputation: 917

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.

Upvotes: 0

Views: 2396

Answers (4)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

String functions strrpos and substr are enough for this task. And its surely faster.

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

Explanation:

  1. strrpos finds the position of . from the end of the string.
  2. substr extracts a sub string till the position of . found in previous step.

When this will work?

Works on http://example.com/forum/index.php?topic=53.msg251#msg251
Works on 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

Upvotes: 4

deed02392
deed02392

Reputation: 5022

Quite simple using the http_build_url function (requires 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);
?>

Upvotes: 0

Toto
Toto

Reputation: 91415

If you want to remove, use preg_replace:

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

Upvotes: 1

OrangeTux
OrangeTux

Reputation: 11471

"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."

link

Preg_Match checks only if the pattern exists in the string. It doesn't remove something.

You can use str_replace() for replacing that part

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

Upvotes: -1

Related Questions