\"h-llo\" but \"h\\ello\" should be \"hello\" any id开发者_运维知识库eas if this is" />
开发者

php: how to replace a letter NOT following a backslash

开发者 https://www.devze.com 2023-01-15 02:00 出处:网络
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 id开发者_运维知识库eas if this is

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 id开发者_运维知识库eas if this is possible with a single regex?


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)


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

$string = preg_replace('/(?<!\\)e/', "-", $string);
0

精彩评论

暂无评论...
验证码 换一张
取 消