简体   繁体   中英

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;

Use this:

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

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

Use this one.

$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:

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);
$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM