Pas*_*TIN 77
这里不需要正则表达式,如果你只想用另一个字符串替换一段字符串:使用str_replace()应该绰绰有余:
$new = str_replace(' ', '%20', $your_string);
Run Code Online (Sandbox Code Playgroud)
但是,如果你想要更多,而且你可能会这样做,如果你正在使用URL,你应该看看这个urlencode()功能.
Mad*_*iha 33
使用urlencode()而不是尝试实现自己的.偷懒.
dro*_*nda 27
我认为你必须使用rawurlencode()代替urlencode().
样品
$image = 'some images.jpg';
$url = 'http://example.com/'
Run Code Online (Sandbox Code Playgroud)
随着urlencode($ str)将导致
echo $url.urlencode($image); //http://example.com/some+images.jpg
Run Code Online (Sandbox Code Playgroud)
它根本不会改为%20
但是使用rawurlencode($ image)会产生
echo $url.rawurlencode(basename($image)); //http://example.com/some%20images.jpg
Run Code Online (Sandbox Code Playgroud)
Vyk*_*tor 15
你有几个选择如何做到这一点,或者:
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)
Run Code Online (Sandbox Code Playgroud)
preg_replace()你在这里几乎没有选择,要么只是~ ~替换空间,要么替换空格和制表符~[ \t]~或各种空格 ~\s~:
return preg_replace( '~\s~', '%20', $text);
Run Code Online (Sandbox Code Playgroud)
或者当你需要"\t \t \t \t"用一个替换这样的字符串时%20:
return preg_replace( '~\s+~', '%20', $text);
Run Code Online (Sandbox Code Playgroud)
我假设你真的想要使用手动字符串替换并处理更多类型的空格,例如不可破坏的空格( )
| 归档时间: |
|
| 查看次数: |
101767 次 |
| 最近记录: |