preg_match - 从url中提取字符串

时间:2011-01-16 21:09:35

标签: php preg-match

我的网址是这样的:

http://localhost/adminator/index.php?section=1portal&tool=2firmyhttp://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26

我希望能够提取SECTION和TOOL参数。

我想出了这个:

preg_match('/(.*)(section=)(.*)(&tool=)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];

但这仅适用于第一个网址,而不适用于第二个网址,而不是我的网址:

preg_match('/(.*)(section=)(.*)(&tool=)(.*)(&)(.*)/', $_SERVER['HTTP_REFERER'], $matchesarray);
echo $section = $matchesarray[3].'<br />';
echo $tool = $matchesarray[5];

这只适用于第二个网址,而不是第一个网址。

如何在两种情况下都能使它工作?感谢。

3 个答案:

答案 0 :(得分:1)

$url = 'http://localhost/adminator/index.php?section=1portal&tool=2firmy&passedID=26';
$url = parse_url($url, PHP_URL_QUERY);
parse_str($url, $output);
echo $output['section']; // 1portal
echo $output['tool']; // 2firmy

答案 1 :(得分:0)

你不能只使用$ _GET ['section']和$ _GET ['tool']吗?

答案 2 :(得分:0)

'section=(.+?).*?&tool=(.+?)'应该有效,然后检查第1组和第2组的值

相关问题