我有一组这样的字符串:
$string1 = 'man_city/man_united'; //it will be replaced
$string2 = 'liverpool///arsenal'; //it will not be replaced
$string3 = 'chelsea//spurs'; //it will not be replaced
$string4 = 'leicester/sunderland'; //it will be replaced
我想用“/”替换字符串中的“/”字符,但前提是“/”字符中的下一个或上一个字符也不包含“/”。
如果我这样使用 str_replace,它不会工作:
$name1 = str_replace("/","\/",$string1);
$name2 = str_replace("/","\/",$string2);
...
//output
$name1 = 'man_city\/man_united';
$name2 = 'liverpool\/\/\/arsenal';
...
//desired output
$name1 = 'man_city\/man_united';
$name2 = 'liverpool///arsenal';
...
最佳答案
你可以使用
'~(?<!/)/(?!/)~'
参见 regex demo .
(?<!/)
如果存在 /
,负向后看将导致匹配失败之前/
和 (?!/)
如果存在 /
,否定前瞻将使匹配失败在 /
之后.
PHP demo :
$re = '~(?<!/)/(?!/)~';
$str = "man_city/man_united\nliverpool///arsenal\nchelsea//spurs\nleicester/sunderland";
$result = preg_replace($re, "\\/", $str);
echo $result;
输出:
man_city\/man_united
liverpool///arsenal
chelsea//spurs
leicester\/sunderland
关于php - 如果仅前一个或下一个字符不包含相同字符,则替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988819/