我有一个包含以下内容的字符串
http://www.mysite.com/test.php?http://www.anotherwebsite.com
如何将第二个url保存在php变量中?
我的意思是,讯问标记后的网址。
如果您有以下
$double_url = 'http://www.mysite.com/test.php?http://www.anotherwebsite.com';
那么你可以做这个
$second_url = substr(strstr($double_url, '?http'), 1);
或者这个
$second_url = preg_replace('/.*'?(http.*)/', '$1', $double_url);
或者这个
$second_url = substr($double_url, strpos($double_url, '?http')+1);
或者许多其他方法都会给你同样的结果。
我关心使用?作为URL之间的分隔符,因为?是完整URI中有效且重要的一部分。出于这个原因,我的示例使用'?http'
而不仅仅是'?'
,但即使使用'?http'
也存在潜在的陷阱情况
你很幸运,PHP有这样的函数!它们被称为strpos()和substr(),它们就是这样工作的:
$haystack = "http://www.mysite.com/test.php?http://www.anotherwebsite.com";
$needle = "?";
$needle_pos = strpos($haystack,$needle);
$text_after_needle = substr($haystack,$needle_pos+1);
实际上有很多方法可以做到这一点。它可以通过explode()和抓取第二个数组元素来完成。它也可以使用正则表达式来完成。上面的代码只是一种简单的方法,可以搜索字符串中的一个字符并获取之后的任何文本。
其中:
$url = 'http://www.mysite.com/test.php?http://www.anotherwebsite.com';
尝试:
$url2 = end(explode('?',$url));
然后:
echo $url2;
将是:
http://www.anotherwebsite.com
试试这个例子。
<?php
$url = "http://www.mysite.com/test.php?http://www.anotherwebsite.com";
$params = parse_url($url);
$otherSite = $params['query'];
echo $otherSite;
?>