PHP更改数组格式以适应URL

4
我正在进行一个奇怪的项目。我对php完全没有经验,所以到目前为止一直很困难。
我有一个表单,它提供一个数组并发布它:
...
return($keywords);
}

$keywordlist = explode("\r\n", $keywordlist);
foreach($keywordlist as $keyword){
print_r(mixer(strtolower($keyword)));
}

我理解为:“我得到了这个。”
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6] => ....

但是我希望它变成这样:
%28one%2Ctwo%2Cthree%2Cfour%2Cfive%2Csix%29

最终希望能够将它附加到像ask.com搜索这样的URL的末尾:
"http://www.ask.com/web?q=(put my keywords here)"

然后导航到那里

理论上,就像我在搜索栏中输入“(one,two,three,four,five,six)”并按回车键一样。

希望这有些意义。


使用 urlencode 函数将特殊字符如 &? 和其他在查询字符串中使用的字符进行编码。 - Salman A
7个回答

7

类似这样:

$commaSeparated = implode(',', $array);
$withParens = '(' + $commaSeparated + ')';
$urlEncoded = urlencode($withParens);
print $urlEncoded;

3

使用php的implode()函数。

因此,您可以这样做:

$array = new array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six );
$string = '%28'.implode( '%2C', $array ).'%29';

现在$string将是您所需的内容。

2
$keywordlist = explode("\r\n", $keywordlist);    
array_walk($keywordlist, 'strtolower');
$keywords = '('.implode(",", $keywordList).')';

2

这段代码:

$keywords = array('one', 'two', 'three');
$query = '(' . implode(',', $keywords) . ')';
echo('Search query: ' . $query . PHP_EOL);
$query = rawurlencode($query);
echo('Encoded: ' . $query . PHP_EOL);

给出以下输出结果:
搜索查询:(one,two,three)已编码为:%28one%2Ctwo%2Cthree%29

2

像这样的内容吗?

(注:已保留HTML标签)
$input = array('one', 'two', 'three');
$s = implode(',', $input);
$s = '('.$i.')';
print urlencode($s);

2

print_r是打印数组的函数,可以将数组以这种方式打印出来。

http://php.net/manual/en/function.print-r.php

如何解决问题取决于几个因素。 mixer()函数做什么?关键字始终小写吗?如果mixer不起作用且关键字为小写,则可以执行以下操作:

$string = '%28' . implode('%2C', $keyword) . '%29';

如果您要进行URL编码,则可以使用函数url_encode而不是手动添加已编码值。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接