如何在 PHP 中移动带有 preg_replace 或 preg_match 的子字符串?
How to move a substring with preg_replace or preg_match in PHP?
我想找到一个子字符串并将其移动到字符串中而不是替换(例如,将其从字符串的开头移动到字符串的结尾)。
'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);
应该有一种使用一个正则表达式来执行此操作的更简单的方法。
您可以使用
$re = '/^(THIS)\b\s*(.*)/s';
$str = 'THIS the rest of the string';
$result = preg_replace($re, ' ', $str);
参见regex demo and a PHP demo。
详情
^
- 字符串开头
(THIS)
- 第 1 组(从替换模式中引用 </code>):<code>THIS
\b
- 单词边界(如果不需要整个单词,可以去掉)
\s*
- 0+ 个空格(如果始终至少有一个空格,请使用 \s+
并删除 \b
,因为它会变得多余)
(.*)
- 第 2 组(从替换模式中引用 </code>):字符串的其余部分(<code>s
修饰符允许 .
匹配换行符,也是)。
我想找到一个子字符串并将其移动到字符串中而不是替换(例如,将其从字符串的开头移动到字符串的结尾)。
'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);
应该有一种使用一个正则表达式来执行此操作的更简单的方法。
您可以使用
$re = '/^(THIS)\b\s*(.*)/s';
$str = 'THIS the rest of the string';
$result = preg_replace($re, ' ', $str);
参见regex demo and a PHP demo。
详情
^
- 字符串开头(THIS)
- 第 1 组(从替换模式中引用</code>):<code>THIS
\b
- 单词边界(如果不需要整个单词,可以去掉)\s*
- 0+ 个空格(如果始终至少有一个空格,请使用\s+
并删除\b
,因为它会变得多余)(.*)
- 第 2 组(从替换模式中引用</code>):字符串的其余部分(<code>s
修饰符允许.
匹配换行符,也是)。