Reputation:
I am trying to strip everything that follows and includes the last ?
of a given url. I am currently working with preg_replace
but no luck in accomplishing the goal. This is the regex #\/[^?]*$#
I am using to single out the last ?
. Also is there a faster way by using substr
?
Example link:
preg_replace('#\/[^?]*$#', '', $post="www.exapmle.com?26sf213132aasdf1312sdf31")
Desired Output
www.example.com
Upvotes: 0
Views: 1149
Reputation: 26667
Add a \?
at start of regex instead of \/
\?[^?]*$
\?
matches a ?
[^?]*$
matches anything other than a ?
until the end of string anchored by $
Example http://regex101.com/r/sW6jE7/3
$post="www.exapmle.com?26sf213132aasdf1312sdf31";
$res=preg_replace('/\?[^?]*$/', '', $post);
echo $res;
will give an output
www.example.com
EDIT
If you want to remove the entire query string from url then a slight modifiation of regex would do the work
\?.*$
which will remove anything followed by a question mark
Upvotes: 0
Reputation: 54212
Although OP tags regex, Surprisingly nobody suggests explode()
, which is much easier.
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$tokens = explode('?', $post);
echo $tokens[0]; // www.exapmle.com
Upvotes: 0
Reputation: 27202
Try this its working fine :
$host_url = "www.exapmle.com?26sf213132aasdf1312sdf31";
$part_url = strrpos($host_url, '?');
$result = substr($host_url, 0, $part_url);
echo $result;
Upvotes: 0
Reputation: 174706
Simply match everything from the start upto the ?
symbol.
preg_match('/^[^?\n]*/', $post="www.exapmle.com?26sf213132aasdf1312sdf31", $match);
echo $match[0];
Output:
www.exapmle.com
Upvotes: 0
Reputation: 3328
Here's how to do it with substr
and strrpos
:
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$pos = strrpos($post, '?');
$result = substr($post, 0, $pos);
Upvotes: 1