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
2010-09-08 14:08:44
+1 for `strtr`.
Daniel Vandersluis
2010-09-08 14:28:46
Would give another +1 for `strtr()` if I could.
BoltClock
2010-09-08 14:29:10
+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
2010-09-08 14:11:00
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
2010-09-08 14:14:29
You don't even need a second regex for that, just use `str_replace('\\', '', $your_string)`
ApoY2k
2010-09-08 14:20:39