Php 替换href中字符串中的空格

Php 替换href中字符串中的空格,php,string,replace,preg-replace,spaces,Php,String,Replace,Preg Replace,Spaces,如何将a href中的空格替换为%20 我准备好了:(它不仅替换href属性中的空格) 函数回调($string){ $string=substr($string,0,-2); $string=substr($string,9); $string=preg_replace('/\s+/','%20',$string); $string=''; 返回$string; } $suchen='()s'; echo preg_replace_callback($suchen,create_函数($tre

如何将a href中的空格替换为%20

我准备好了:(它不仅替换href属性中的空格)

函数回调($string){
$string=substr($string,0,-2);
$string=substr($string,9);
$string=preg_replace('/\s+/','%20',$string);
$string='';
返回$string;
}
$suchen='()s';
echo preg_replace_callback($suchen,create_函数($treffer','return callback($treffer[0])),$new7);

“$new7”是旧字符串。

假设您的href属性总是被引用,您可以使用以下模式:

$pattern = '~(?>\bhref\s*=\s*["\']|\G(?<!^))[^ "\']*+\K ~';
$result = preg_replace($pattern, '%20', $html);

$pattern='~(?>\bhref\s*=\s*[“\']\124;\ G(?如果您想使字符串url安全,首选方法是使用%20和其他讨厌的东西替换空格。示例:

echo';

$string=preg\u replace('/\s+/','%20',$string);
可能只是
$string=str\u replace(''''%20',$string);
@johncode这也行,但这并不是其他空格不可用的原因replaced@qwertz1029384756:什么不起作用?你能给我们展示一个URL不起作用的例子吗?@AmalMurali it一直在替换spaces@qwertz1029384756:这不是你想要做的吗(替换空格?)+1对于
urlencode()
,但是,在本例中,我不确定OP是否有权访问
$userinput
$pattern = '~(?>\bhref\s*=\s*["\']|\G(?<!^))[^ "\']*+\K ~';
$result = preg_replace($pattern, '%20', $html);
~
(?>                     # open an atomic group (*)
    \bhref\s*=\s*["\']  # attribute name until the quote
  |                     # OR
    \G(?<!^)            # contiguous to a precedent match
)                       # close the atomic group
[^ "\']*+               # content that is not a space or quotes (optional) 
\K                      # resets the start of the match from match result
[ ]                     # a space
~
echo '<a href="mycgi?foo=', urlencode($userinput), '">';