我有一套这样的绳子:
$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';
...发布于 2018-02-26 12:49:53
你可以用
'~(?<!/)/(?!/)~'见regex演示。
如果在(?<!/)之前有/,则/负查找将导致匹配失败,如果在/之后有/,则(?!/)负查找将导致匹配失败。
$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\/sunderlandhttps://stackoverflow.com/questions/48988819
复制相似问题