我希望用%20替换url中的所有空格实例。我将如何使用正则表达式做到这一点?
谢谢!
这里不需要正则表达式,如果你只是想用另一个字符串替换一段字符串:使用 str_replace()
应该绰绰有余:
$new = str_replace(' ', '%20', $your_string);
但是,如果你想要更多的东西,如果你正在使用URL,你应该看看urlencode()
函数。
我认为你必须使用rawurlencode((而不是urlencode((来实现你的目的。
样本
$image = 'some images.jpg';
$url = 'http://example.com/'
使用urlencode($str(将产生
echo $url.urlencode($image); //http://example.com/some+images.jpg
它根本不会变成 %20
但使用rawurlencode($image(将产生
echo $url.rawurlencode(basename($image)); //http://example.com/some%20images.jpg
使用urlencode()
而不是尝试实现自己的。要偷懒。
您有几种选择来执行此操作:
-
urlencode()
或rawurlencode()
- 旨在对 http 协议的 URL 进行编码的函数 -
str_replace()
- "重型机械"字符串替换 -
strtr()
- 替换多个字符时的性能会比str_replace()
更好 -
preg_replace()
使用正则表达式(与perl兼容(
strtr()
假设您要将"'t"
和" "
替换为"%20"
:
$replace_pairs = array(
"'t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
您在这里几乎没有选择,要么只替换空格~ ~
,再次替换空格和制表符~[ 't]~
,要么~'s~
各种空格:
return preg_replace( '~'s~', '%20', $text);
或者当您需要仅用一个%20
替换这样的字符串"'t 't 't 't"
时:
return preg_replace( '~'s+~', '%20', $text);
我假设您真的想使用手动字符串替换并处理更多类型的空格,例如不可破坏的空间 (
(
public static function normalizeUrl(string $url) {
$parts = parse_url($url);
return $parts['scheme'] .
'://' .
$parts['host'] .
implode('/', array_map('rawurlencode', explode('/', $parts['path'])));
}
$result = preg_replace('/ /', '%20', 'your string here');
您也可以考虑使用
$result = urlencode($yourstring)
也转义其他特殊字符