Andrew Bro
Andrew Bro

Reputation: 491

Get the leading part of a URL string before the first ampersand

I need to parse the following string:

$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';

It's dynamic and could contain more &-symbols.

I want to get everything but the part starting from "&..." so the result should be:

http://test.al/admin/?plugin=pages

Upvotes: 0

Views: 51

Answers (3)

Rajdeep Paul
Rajdeep Paul

Reputation: 16963

Use parse_url() for this:

$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';

$url_components = parse_url($str);
$get_component = explode("&", $url_components['query']);

$new_str = $url_components['scheme'] . "://" . $url_components['host'] . $url_components['path'] . "?" . $get_component[0];
echo $new_str;

Output:

http://test.al/admin/?plugin=pages 

Upvotes: 0

D4V1D
D4V1D

Reputation: 5849

Use strtok():

<?php
$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
$result = strtok($str, '&');

var_dump($result); // outputs "http://test.al/admin/?plugin=pages"

Upvotes: 2

RST
RST

Reputation: 3925

$parts = explode('&', $str);
$str = $parts[0];

Convert the string to an array by using & as delimiter. The first element of the array will hold the part you need

Upvotes: 1

Related Questions