【问题标题】:Replace spaces from string in href替换href中字符串的空格
【发布时间】:2013-11-23 21:05:28
【问题描述】:

如何用 %20 替换 href 中的空格?

我已经知道了:(它不仅替换了 href 属性中的空格)

function callback($string){
$string = substr($string,0, -2);
$string = substr($string, 9);
$string = preg_replace('/\s+/','%20',$string);
$string = '<a href="'.$string.'">';
return $string;
}
$suchen = '(<a href="(.*?)">)s';
echo preg_replace_callback($suchen,create_function('$treffer','return callback($treffer[0]);'),$new7);

"$new7" 是旧字符串。

【问题讨论】:

  • $string = preg_replace('/\s+/','%20',$string); 可能只是$string = str_replace(' ','%20',$string);
  • @JohnConde 这也可以,但这不是替换其他空格的原因
  • @qwertz1029384756:到底是什么不工作?您能否向我们展示一个未按预期工作的 URL 示例?
  • @AmalMurali |%20AFK%20| 
    它不断替换空格
  • @qwertz1029384756:这不是你想要做的(替换空格?)

标签: php string replace preg-replace spaces


【解决方案1】:

如果您想要使字符串 url 安全,首选方法是使用 urlencode() 将空格替换为 %20 和其他讨厌的东西。来自in the documentation的例子:

echo '<a href="mycgi?foo=', urlencode($userinput), '">';

【讨论】:

  • +1 表示urlencode(),但是,在本例中,我不确定 OP 是否可以访问 $userinput
【解决方案2】:

假设你的 href 属性总是被引用,你可以使用这个模式:

$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
~

(*) atomic group 是一个非捕获组,不允许正则表达式引擎回溯。

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签