比用HTML 实体替换可破坏空格更安全的选择是用\xA0
ASCII 字符替换它。他们实际上是平等的。an 中的&
字符URL
被视为参数分隔符,因此
只会导致问题。以下算法可以做你可能正在寻找的东西:
$url = 'http://www.site.com/index.php?q=foo boo&r=fii bii';
echo str_replace("\x20", "\xA0", $url);
// result: http://www.site.com/index.php?q=foo boo&r=fii bii (spaces are non-breakable)
echo str_replace("\x20", " ", $url);
// result: http://www.site.com/index.php?q=foo boo&r=fii bii
更复杂的算法:
echo preg_replace_callback('/[\?&]\w+=([^&]+)/', create_function(
'$matches',
'return str_replace("\x20", "\xA0", $matches[0]);'
), $url);
// result: http://www.site.com/index.php?q=foo boo&r=fii bii (spaces are non-breakable)
当这些参数被提取出来时:
$arr = parse_url($url);
parse_str($arr['query'], $arr);
var_export($arr);
// result for \xA0 : array ( 'q' => 'foo boo', 'r' => 'fii bii', )
// result for : array ( 'q' => 'foo', 'nbsp;boo' => '', 'r' => 'fii', 'nbsp;bii' => '', ) // triple `&` in conflict