我要求用户在文本框中输入一个URL,并需要在其中附加一个查询字符串.
URL的可能值可以是:
现在我需要像"q2 = two"一样添加查询字符串,这样输出就像:
如何使用PHP实现以下功能?
ale*_*lex 34
<?php
$urls = array(
'http://www.example.com',
'http://www.example.com/a/',
'http://www.example.com/a/?q1=one',
'http://www.example.com/a.html',
'http://www.example.com/a.html?q1=one'
);
$query = 'q2=two';
foreach($urls as &$url) {
$parsedUrl = parse_url($url);
if ($parsedUrl['path'] == null) {
$url .= '/';
}
$separator = ($parsedUrl['query'] == NULL) ? '?' : '&';
$url .= $separator . $query;
}
var_dump($urls);
Run Code Online (Sandbox Code Playgroud)
array(5) {
[0]=>
string(29) "http://www.example.com/?q2=two"
[1]=>
string(32) "http://www.example.com/a/?q2=two"
[2]=>
string(39) "http://www.example.com/a/?q1=one&q2=two"
[3]=>
string(36) "http://www.example.com/a.html?q2=two"
[4]=>
&string(43) "http://www.example.com/a.html?q1=one&q2=two"
}
Run Code Online (Sandbox Code Playgroud)
Rap*_*tor 13
$ url是您的网址.使用strpos功能
if(strpos($url,'?') !== false) {
$url .= '&q2=two';
} else {
$url .= '?q2=two';
}
Run Code Online (Sandbox Code Playgroud)
我知道这是旧的,但我改进了亚历克斯的答案,以解释字符串的"#"部分.
$urls = array(
'http://www.example.com',
'http://www.example.com/a/#something',
'http://www.example.com/a/?q1=one#soe',
'http://www.example.com/a.html',
'http://www.example.com/a.html?q1=one'
);
$query = 'q2=two';
foreach($urls as &$url) {
$pound = "";
$poundPos = -1;
//Is there a #?
if ( ( $poundPos = strpos( $url, "#" ) ) !== false )
{
$pound = substr( $url, $poundPos );
$url = substr( $url, 0, $poundPos );
}
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$url .= $separator . $query . $pound;
}
var_dump($urls);
Run Code Online (Sandbox Code Playgroud)