代码之家  ›  专栏  ›  技术社区  ›  Googlebot

如何在PHP中用preg\u replace或preg\u match移动子串?

  •  1
  • Googlebot  · 技术社区  · 6 年前

    我想找到一个子串并在字符串中移动它,而不是替换它(例如,将它从字符串的开头移动到结尾)。

    'THIS the rest of the string' -> 'the rest of the string THIS'
    

    我通过以下代码来实现

    preg_match('/^(THIS).?/', $str, $match);
    $str = trim( $str . $match[1] );
    $str = preg_replace('/^(THIS).?/', '', $str);
    

    使用一个正则表达式应该有一个更简单的方法。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Wiktor Stribiżew    6 年前

    你可以用

    $re = '/^(THIS)\b\s*(.*)/s';
    $str = 'THIS the rest of the string';
    $result = preg_replace($re, '$2 $1', $str);
    

    看到了吗 regex demo 和一个 PHP demo .

    细节

    • ^ -字符串开头
    • (THIS) -组1(参考 $1 从替换模式): THIS
    • \b -单词边界(如果您不需要整个单词,可以删除它)
    • \s* \s+ 并移除 ,因为它将变得多余)
    • (.*) -第2组(参考 $2 s 修饰符允许 .