【问题标题】:PHP replace string starting with xxx and ending with yyy after 5 charactersPHP替换以xxx开头并在5个字符后以yyy结尾的字符串
【发布时间】:2021-07-22 15:20:16
【问题描述】:

输入:

$str = 'hi test1="12c4 ab3d" blablabla test1="5678 sdfg"'

所以我需要在 5 个字符后删除 'test1="' 和 '"' 之间的字符串,如下所示:

'hi test1="12c4" blablabla test1="5678"'

我已经试过了:

$str= preg_replace('/test1="[\s\S]+?"/', 'test1=""', $str);

但我的输出是:

'hi test1="" blablabla test1=""'

【问题讨论】:

    标签: php string replace preg-replace


    【解决方案1】:

    或者,不使用正则表达式并使用简单的strpos()substr()

    $str = 'hi test1="12c4 ab3d" blablabla test1="5678 sdfg"';
    
    $find = 'test1=';
    $p1 = stripos($str, $find) + strlen($find)+5;
    $p2 = strripos($str, $find) + strlen($find)+5;
    
    $new =  substr($str, 0, $p1) . substr($str, $p1+5, $p2-$p1-5) . substr($str, $p2+5);
    echo $new . PHP_EOL;
    

    【讨论】:

      【解决方案2】:

      你可以使用

      $str = 'hi test1="12c4 ab3d" blablabla test1="abcd 3456 sdfs 2435"';
      echo preg_replace('~\btest1="[^"\s]*\K[^"]+~', '', $str);
      // => hi test1="12c4" blablabla test1="abcd"
      

      请参阅PHP demoregex demo

      详情

      • \b - 单词边界
      • test1=" - 文字文本
      • [^"\s]* - 除空格和" 之外的零个或多个字符
      • \K - 匹配重置运算符,从匹配内存缓冲区中删除到目前为止匹配的文本
      • [^"]+ - 除了" 之外的一个或多个字符。

      【讨论】:

      • 感谢您的回答。如果 test1 更长怎么办?比如 test1="abcd 3456 sdfs 2435"
      • @user16405471 我调整了答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多