简体   繁体   中英

php: how to replace a letter NOT following a backslash

您好,我想将字符串中的所有“ e”替换为“-”而不是反斜杠,因此“ hello”应该是->“ h-llo”,但是“ h \\ ello”应该是“ hello”任何想法一个正则表达式是可能的?

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 )

您可以在后面使用负号,以确保e之前的字符不是反斜杠:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM