Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php将URL的一部分转换为字符串_Php_Regex - Fatal编程技术网

php将URL的一部分转换为字符串

php将URL的一部分转换为字符串,php,regex,Php,Regex,嗨,伙计们,我用这个代码来获取我的url上的id $string = $url; $matches = array(); preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches); $id = $matches[1][0]; 此代码适用于URL,如 http://mysite.com/page/1 http://mysite.com/page/somepage/2 http://mysite.com/page/3/?pag=1 我会让id=

嗨,伙计们,我用这个代码来获取我的url上的id

$string = $url;
$matches = array();
preg_match_all('/.*?\/(\d+)\/?/s', $string, $matches);

$id = $matches[1][0];
此代码适用于URL,如

http://mysite.com/page/1
http://mysite.com/page/somepage/2
http://mysite.com/page/3/?pag=1
我会让id=1/id=2/id=3

但是对于这样的url

http://mysite.com/page/122-page-name/1
这将返回id=122

我尝试获取的id将始终是url的最后一部分,或者在url之后有/?p=个id

这样我就可以拥有URL类型了

http://mysite.com/page/1
http://mysite.com/page/some-page/2
http://mysite.com/page/12-some-name/3
http://mysite.com/page/some-page/4/?p=1
http://mysite.com/page/13-some-page/5/?p=2

id=1/id=2/id=3/id=4/id=5

如果您的id始终位于url的末尾,您可以
分解url的内容并获取结果数组的最后一个元素。如果它可能包括变量(如
?pag=1
),则可以在
分解后添加验证以检查变量

$urlArray = explode('/', $url);
$page = end($urlArray);
if(strpos($page, 'pag')!==false){
    //get the contents of the variable from the $page variable
    //exploding the variable through the ? variable and getting
    //the numeric characters at the end
}

我更倾向于URL解析,而不是尝试使用正则表达式,尤其是当您需要处理各种各样的(有效的)URL时

end(array_filter(explode('/', parse_url($url, PHP_URL_PATH))));

array\u过滤器
处理跟踪斜杠

因为它总是在末尾或后面有?p=x,所以可以执行以下操作:

$params = explode('/', $_SERVER['REQUEST_URI']);
$c = count($params);
if (is_int($params[$c - 1])  
    $id = $params[$c - 1];
else
    $id = $params[$c - 2];

不是直接的回答,更多的是“如何为自己解决这个问题”的回答:]


将此代码放在页面顶部,放在任何其他代码之前(但在
@AlvaroLouzada之后不应该。它应该设置
$id=$params[$c-1]
,这将是最后一个。不过我会仔细检查。
foreach($_SERVER as $k => $v) {
    echo $k.' = '.$v.'<br />';
}
exit;