问题
I am trying to collect all CatIDs from a site...the URL structure is...
http://www.abc.com/family/index.jsp?categoryId=12436777
I am interested in it categoryId
which is in this case is 12436777
My question is
Which is best, Regex or string explode??
if regex, please help me, I am very bad on it..
Also, I have to consider that URLs like
http://www.abc.com/product/index.jsp?productId=12282785
I tried
$array = explode("http://www.abc.com/family/index.jsp?categoryId=", $loc);
foreach ($array as $part) {
$zee[] = $part[1];
}
but it gives me nothing ..
thanks for help..
回答1:
You can use parse_url to reliably give you the query string:
$parts = parse_url('http://www.abc.com/family/index.jsp?categoryId=12436777');
and then parse_str to parse out the variables:
parse_str($parts['query'], $result);
echo $result['categoryId']; // outputs 12436777
回答2:
You can use the following regex:
http://.+?Id=(\d+)
The 1st group will contain the ID you're looking for.
回答3:
How about:
$url_parts = parse_url('http://www.abc.com/family/index.jsp?categoryId=12436777');
if (isset($url_parts['query'])) {
$query_parts = explode('&', $url_parts['query']);
$keys = array();
foreach ($query_parts as $part) {
$item = explode('=', $part);
$keys[$item[0]] = $item[1];
}
$category_id = isset($keys['categoryId']) ? $keys['categoryId'] : 0;
}
回答4:
try...
list(,$id) = explode('=','http://www.abc.com/product/index.jsp?productId=12282785');
this will work if there's 1 =
in the string
回答5:
explode' s first param is the separator item. If you want to use it, try with something like:
$loc = "http://www.abc.com/family/index.jsp?categoryId=12436777";
$res=explode("=", $loc);
and the id will be in $res[1]
回答6:
Code:
$url = "http://www.abc.com/family/index.jsp?categoryId=12436777";
$parts = Explode('=', $url);
$id = $parts[count($parts) - 1];
Demonstration:
http://stepolabs.com/lab/explode/index.php
http://stepolabs.com/lab/explode/index.php.txt
回答7:
If you're sure that what , is the only number, just do this
$st = "http://www.abc.com/family/index.jsp?categoryId=12436777";
echo preg_filter('/[^0-9]/','',$st);
来源:https://stackoverflow.com/questions/15100249/getting-a-part-from-a-string