将href中的空格替换为php中的%20


Replace spaces in href with %20 in php

我想用%20替换链接中的每个空格。

<a href="Replace the spaces here">Some text</a>

我想买这个:

<a href="Replace%20the%20spaces%20here">Some text</a>

不是这个:

<a%20href="Replace%20the%20spaces%20here">Some%20text</a>

如何做到这一点?preg_replace?解决方案(因为我无法发布答案):

$search= '(href="(.*?)")s';
$replace= '';
$newstring= preg_replace_callback($search,create_function('$treffer','urlencode($treffer[0]);'),$string);

您应该为href部分使用urlencode()函数。

http://php.net/urlencode

注意,每个现代浏览器都会很好地处理以下内容:

<a href="Replace the spaces here">Some text</a>

如果你坚持无论如何都要这样做,并且假设你不能在输出之前urlencode()链接,你需要使用以下任一项:

  • preg_replace_callback()
  • DOM解析器

使用任意一个都将允许您仅在需要的地方应用urlencode()

你可以试试这个:

<a href="<? echo(urlencode("Replace the spaces here")); ?>">Some text</a>