Search code examples
phphtmlescapingpreg-replacehref

Replace spaces in href with %20 in php


i want to replace every space in a link with %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? Solution (because I cant post an answer):

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

Solution

  • 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:

    • preg_replace_callback() or
    • a DOM parser

    Using either will allow you to only apply urlencode() where it's needed.