Gustavo Benito Silva
Gustavo Benito Silva

Reputation: 543

regular expression to extract a query string parameter value from a URL in PHP

I need to extract an item id from a URL; the pattern is this &R=10031004&, I mean, I need to extract the string within &R= and the other &

This is what I have so far, but I keep getting errors.

preg_match('^[&R=]+ &$',
"http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
$host = $matches[0];

echo $host;

Upvotes: 2

Views: 2364

Answers (7)

Saxoier
Saxoier

Reputation: 1287

$url = "http://www.lapdirecciondemario.com/items.php&R=10031004&";
$urlQueryParts = array();
parse_str(parse_url($url, PHP_URL_QUERY), $urlQueryParts);
if(isset($urlQueryParts[ "R" ]))
    $urlQueryParts[ "R" ];

I couldn't test it but it should work.

Upvotes: 0

user8710
user8710

Reputation:

I might as well chuck another at you. This one will match any character between an R= preceeded by ? or & and ending with & or #.

preg_match('/[?&]R=([^&#]+)/', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);

Upvotes: 0

middus
middus

Reputation: 9121

$url = 'http://www.lapdirecciondemario.com/items.php&R=10031004&';
preg_match('/(&|\?)R=([0-9]+)/i', $url, $matches);
echo $matches[2];

In contrast to the other answers, this will also match if the parameter R is preceded by a ? instead of a &. If you know more about the length of the number, you can replace the + after [0-9] with {min,max}.

This regular expression should be pretty robust and match all of these:

Upvotes: 2

FailedDev
FailedDev

Reputation: 26930

if (preg_match('/(?<=&R=).*?(?=&)/', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $regs)) {
    $result = $regs[0];
}

Use this one.

Upvotes: 0

Aurelio De Rosa
Aurelio De Rosa

Reputation: 22152

Use this:

preg_match('/&R\=(.*?)&/i', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
echo $matches[1]; // will echo 10031004

Upvotes: 1

sharpner
sharpner

Reputation: 3937

well first of all maybe I can simplify your task,

is this the url from the script?

then you should check the contents of $_GET where you will find a variable R with contents 10031004...

$item_id = $_GET['R']; 
echo $item_id; 

Upvotes: 0

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

preg_match('#R=([0-9]+)#is', "http://www.lapdirecciondemario.com/items.php&R=10031004&", $matches);
echo $matches[1]; # 10031004

Upvotes: 0

Related Questions