php - 如果仅前一个或下一个字符不包含相同字符,则替换字符串中的字符

标签 php regex string replace

我有一组这样的字符串:

$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/

相关文章:

php - phpinfo() 中没有 oci8 模块

php - Mysql:如何在事务期间锁定整个表?

java - 使用java将文本和图像发送到php

python - 如何从 python 中的字符串中提取多子字符串?

C++:我用不同的位置两次调用一个字符串 substr,转换为 const char *,它们返回相同,为什么?

php - fatal error : Maximum execution time of 30 seconds exceeded when i execute daily run from my website

javascript - 数据表服务器端排序不工作。出了什么问题?

javascript - 正则表达式 - 数量字段

正则表达式匹配字母字符后跟 4 个字母数字

java - java正则表达式有问题