我想从变量中找到一个ID并将其保存到另一个变量中。但是,这个id在其他所有数字中都处于中间位置,我不知道如何定位它。
$f_contents = file("links.txt");
$url = $f_contents[mt_rand(0, count($f_contents) - 1)];
echo $url;
// $url will output something similar to:
// http://store.steampowered.com/app/24010/?snr=1_5_9__400
// or..
// http://store.steampowered.com/app/275200/?snr=1_5_9__400
// or..
// http://store.steampowered.com/app/275830/?snr=1_5_9__400
// and so on.
// $gameid = 24010; (or the other ids)
如何在app /之前/之后获取该ID号?在这种特殊情况下,24010,275200或275830。
答案 0 :(得分:5)
您可以使用正则表达式:
$url = 'http://store.steampowered.com/app/24010/?snr=1_5_9__400';
preg_match('~/app/(.*)/~', $url, $matches);
echo $matches[1]; //outputs 24010
答案 1 :(得分:3)
以下是如何使用爆炸功能获得您想要的数字($ gameid)。
如果$ url是一个url数组,你应该在foreach中循环。
4.In the Add Filter Mapping dialog, select one of the following dispatcher types:
REQUEST: Only when the request comes directly from the client
FORWARD: Only when the request has been forwarded to a component (see Transferring Control to Another Web Component)
INCLUDE: Only when the request is being processed by a component that has been included (see Including Other Resources in the Response)
ERROR: Only when the request is being processed with the error page mechanism (see Handling Servlet Errors)
答案 2 :(得分:2)
已经有两个非常好的答案,但这是另一个选择。由于它是一个网址,因此您可以使用parse_url:
$parsed = parse_url($url);
会给你一个像这样的数组:
array (size=4)
'scheme' => string 'http' (length=4)
'host' => string 'store.steampowered.com' (length=22)
'path' => string '/app/275200/' (length=12)
'query' => string 'snr=1_5_9__400' (length=14)
然后你可以{app}'关闭'app'并从路径斜杠获取id。
$gameid = trim($parsed['path'], '/app');