我目前正在尝试使用parse_url
格式化网址链接。我的目标是每次在其中包含以下字符&p
(按此顺序)时解析链接。 if statement
可以在决定解析链接之前检查url
中的这些字符。例如,如果链接具有字符&p
(按此顺序),那么它将解析链接并格式化为我想要的选择。我已经能够找到解析部分,但我怎样才能检查这些字符&p
(按此顺序)?如果您看到以下示例,我只想从链接中删除&
。
if($url == '&p' ) // not sure how to check
{
$parsed_url = parse_url($url);
$fragment = $parsed_url['fragment'];
$fragment_parts = explode('/', $fragment);
$formatted_url = array_pop('http://www.website.com?p=$1',$url);
}
else
{
// do something else
}
示例:
输入:http://www.website.com?&p=107
输出:'http://www.website.com?p=107
答案 0 :(得分:2)
您可以使用str_replace function将此&p
字符串替换为p
。
$url = "http://www.website.com?&p=107";
$url = str_replace("&p", "p", $url);
echo $url; // will print http://www.website.com?p=107
对于更复杂的文字处理,您可以使用preg_replace()
。
答案 1 :(得分:1)
如果您只是需要检查网址是否已获得?& p只需使用strpos:
<?php
if(strpos($url, '?&p') !== false) {
//your magic
}
?>
否则,如果您尝试处理错误请求,可以执行以下操作:
<?php
$url = $_SERVER['REQUEST_URI']; // will have the /?&p=123
if(strpos($url, '?&p') !== false) {
$url = str_replace("&p", "p", $url); // now you've only got ?p=123
//then do what ever you like
//redirect to the appropriate URL or you can set the $_GET['p'] e.g.
header("Location: /".$url);
//or
$parsed = parse_str($url, $get);
$_GET['p'] = $get['?p'];
}
?>