【问题标题】:Replace character from string if only previous or next character not containing the same character如果只有前一个或下一个字符不包含相同的字符,则从字符串中替换字符
【发布时间】:2018-02-26 12:44:43
【问题描述】:

我有一组这样的字符串:

$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';
...

【问题讨论】:

  • 放上想要输出的例子。

标签: php regex string replace


【解决方案1】:

你可以使用

'~(?<!/)/(?!/)~'

请参阅regex demo

如果/ 之前有/,则(?&lt;!/) 否定lookbehind 将失败匹配,如果/ 之后有/,则(?!/) 否定lookahead 将失败匹配。

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

【讨论】:

  • @nortonuser 基本上,替换模式中的\ 是一个特殊字符,而文字\ 应该用双文字\ 定义。但由于 / 并没有使转义变得特别,所以只需加倍 \ 就可以了。
【解决方案2】:

在这种情况下,使用正则表达式 (=> preg_replace()) 会更容易。

例如preg_replace(#/+#, '/', $str)

【讨论】:

    【解决方案3】:

    我认为这可以帮助你:

    <?php
    $string1 = 'man_city/man_united'; //it will  be replaced
    
    if(!substr_count($string1, '//')){
       $string1 = str_replace('/','#',$string1); //Do replace accordingly 
    }
    
    echo $string1;
    

    【讨论】:

      【解决方案4】:

      您可以尝试消极的环顾:

      $name = preg_replace("/(?<!\/)\/(?!\/)/","\/",$string1);
      

      Demo

      解释:

      (?<!\/)\/(?!\/)
      
      • (?&lt;!\/)negative lookbehind - 匹配字符串中没有/的位置
      • \/ 匹配“/”
      • (?!\/) 否定前瞻 - 匹配字符串中未跟随 / 的位置 `

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-11
        • 2022-08-08
        • 2019-05-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多