tags:

views:

54

answers:

2

hi i want to replace all "e" in a string with "-" which are NOT following a backslash so "hello" should be -> "h-llo" but "h\ello" should be "hello" any ideas if this is possible with a single regex?

+5  A: 

There is no way but to use the e flag if you need to combine both regexes since the replacement is different.

preg_replace('/(\\\\?e)/e', "'\\1'=='e'?'-':'e'", $str);

(Usage: http://www.ideone.com/S2uiS)

There is no need to use regex though. The strtr function is capable of performing this kind of replacement.

strtr($str, array('\\e' => 'e', 'e' => '-'));

(Usage: http://www.ideone.com/yg93g)

KennyTM
+1 for `strtr`.
Daniel Vandersluis
Would give another +1 for `strtr()` if I could.
BoltClock
+3  A: 

You can use a negative lookbehind to ensure that the character before the e is not a backslash:

$string = preg_replace('/(?<!\\)e/', "-", $string);
Daniel Vandersluis
thx for your fast answer! there was an error thrown by php i have changed it to preg_replace('/(?<!\\\)e/', '-', $str); and it works! thx! but "t\est" now stays "t\est" what i want is "t\est" -> "test". i know i can do this in a second replace function. but is it possible to integrate it in your regex?
lhwparis
No, you need a second replace operation for this.
Tim Pietzcker
You don't even need a second regex for that, just use `str_replace('\\', '', $your_string)`
ApoY2k
Or even `stripslashes($string)`.
BoltClock