Domanda

How can I replace spaces in a href with %20?

I allready got this: (It is replacing not only the spaces in the href attribute)

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" is the old string.

È stato utile?

Soluzione

Assuming that your href attribute is always quoted, you can use this pattern:

$pattern = '~(?>\bhref\s*=\s*["\']|\G(?<!^))[^ "\']*+\K ~';
$result = preg_replace($pattern, '%20', $html);

pattern details:

~
(?>                     # 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
~

(*) An atomic group is a non-capturing group where the regex engine is not allowed to backtrack.

Altri suggerimenti

If what you want is to make the string url-safe, the preferred method is using urlencode() to replace spaces with %20 and other nasty things. From the example in the documentation:

echo '<a href="mycgi?foo=', urlencode($userinput), '">';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top