Coolcrab
Coolcrab

Reputation: 2723

Remove spaces with regex

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

Answers (3)

Jerry
Jerry

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.

regex101 demo.

Upvotes: 0

Amitkumar Arora
Amitkumar Arora

Reputation: 149

Try this regex code to remove white spaces

\s+(?=[^()]*\

Upvotes: 0

hek2mgl
hek2mgl

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

Related Questions