Reputation: 917
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
Reputation: 57650
String functions strrpos and substr are enough for this task. And its surely faster.
$link = substr($linkraw, 0, strrpos($linkraw, "."))
strrpos
finds the position of .
from the end of the string.substr
extracts a sub string till the position of .
found in previous step.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
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
Reputation: 91415
If you want to remove, use preg_replace:
$link = preg_replace('/\..*?$/', '', $linkraw);
Upvotes: 1
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."
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