Reputation: 2723
I want to remove the space between two words with a regex, however this does not seem to work.
$pattern = "#\<a href=\"(.+?) (.+?)\">#is";
$txt = preg_replace($pattern, "\<a href=\"\\1%20\\2\">", $txt);
I also need this to work for multiple words, but only withing the tags, as the rest of the text should have spaces. So a str_replace won't work (I think?)
Any tips?
Upvotes: 0
Views: 93
Reputation: 71538
You can try the regex:
$txt = preg_replace('~(?:href="|(?<!^)\G)\K([^" ]*)\s+~g', "$1%20", $txt);
\G
matches at the end of the previous match so that you can replace multiple spaces in a single attribute.
Upvotes: 0
Reputation: 157992
The stable solution would be: Use DOM to retrieve the href value, use str_replace()
to remove the spaces and then write back the value using DOM again.
Don't use regexes to handle html / xml.
Upvotes: 1