简体   繁体   English

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

[英]Replace spaces in href with %20 in php

i want to replace every space in a link with %20. 我想用%20替换链接中的每个空格。

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

i want to get This: 我想得到这个:

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

not this: 不是这个:

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

How to do this? 这个怎么做? preg_replace? preg_replace函数? Solution (because I cant post an answer): 解决方法(因为我无法发布答案):

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

You should use the urlencode() function for the href part. 您应该为href部分使用urlencode()函数。

http://php.net/urlencode http://php.net/urlencode

For the note, every modern browser will process the following just fine: 需要注意的是,每个现代的浏览器都将处理以下内容:

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

If you insist in doing it regardless, and assuming you cannot urlencode() the links before they're output, you need to use either of: 如果您坚持要这样做,并且假设在链接输出之前不能对链接进行 urlencode() ,则需要使用以下任一方法:

  • preg_replace_callback() or preg_replace_callback()
  • a DOM parser DOM解析器

Using either will allow you to only apply urlencode() where it's needed. 使用这两种方法将只允许您在需要的地方应用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