tags:

views:

315

answers:

4

I'm a newcomer to regular expressions, and am having a hard time with what appears to be a simple case.

I need to replace "foo bar" with "fubar", where there is any amount and variety of white space between foo and bar.

For what it's worth, I'm using php's eregi_replace() to accomplish this.

Thanks in advance for the help.

+8  A: 

... = preg_replace('/foo\s+bar/', 'fubar', ...);

drdaeman
Oh, and if you want to replace 'foobar' too, you have to use \s* instead of \s+. "*" means "zero or more times" (the "*" symbol came directly from http://en.wikipedia.org/wiki/Kleene_star), and "+" means "one or more time". "\s" stands for "any whitespace character". Plain unescaped alphanumerics have no special meaning.
drdaeman
It is a good idea to use preg_* (like drdaeman has used) instead of ereg_*. The former uses perl-compatible regular expressions (PCRE), which are the de facto standard now and far-better documented on the webs.
BipedalShark
This expression performs exactly as I'd hoped. Thanks drdaeman, and others, for the help, and for the helpful extra comments.
Lasoldo Solsifa
Oh, didn't notice you've said ereg*i*. If you need to make regexp case insensitive use "i" flag in regexp: preg_replace('/foo\s+bar/i', ...)
drdaeman
wouldn't the pattern be better if it looked more like this? ... = preg_replace( '/(\w+)\s+(\w+)/', '\\1\\2', ...);
KOGI
Well, I understood it that he needs to replace "foo bar" with "fubar" (not "foobar", which your code would do). So, that's exactly what I wrote.
drdaeman
+1  A: 

I'm not sure about the eregi_replace syntax, but you'd want something like this:

Pattern: foo\s*bar
Replace with: fubar
Johnny G
A: 

Try this:

find = '(foo)\s*(bar)'
replace = '\\1\\2'

\s is the metachar for any whitespace character.

JoshKraker
Good example on using capturing brackens, but Lasoldo Solsifa wants to replace "foo bar" with "fubar", not "foobar".
drdaeman
A: 

I also prefer preg_replace, but for completeness, here it is with ereg_replace:

$pattern     = "foo[[:space:]]+bar";
$replacement = "fubar";
$string = "foo    bar";
print ereg_replace( $pattern, $replacement, $string);

that prints "fubar"

artlung
Actually, $pattern = "foo[[:space:]]+bar"; $replacement = "fubar";. Otherwise it will happily replace "foo baz" too, which is probably not something we want.
drdaeman
@drdaeman - ouch! good point! fixed.
artlung