繁体   English   中英

用PHP中的%20替换href中的空格

[英]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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM