Regex删除字符串中三个或更少字符单词的第一个字符


Regex remove first character of three or lesser character words in a string

我有+a +string +of +words +with +different +lengths

这样的字符串

我想使用php的preg_replace删除+仅从单词是1 - 3个字符长,包括+。要求输出为a +string of +words +with +different +lengths

如果不捕获组,

(?<= |^)'+(?='w{1,3}'b)

演示

你最终的PHP代码是:

<?php
$string = '+a +string +of +words +with +different +lengths';
$pattern = "~(?<= |^)'+(?='w{1,3}'b)~";
$replacement = "";
echo preg_replace($pattern, $replacement, $string);
?>
输出:

a +string of +words +with +different +lengths

解释:

(?<= |^)'+(?='w{1,3}'b)
  • (?<= |^)正向后看,只看起始点或空间。
  • '+ A文字+符号
  • (?='w{1,3}'b) +符号后面的字符必须是(1到3)个单词字符,然后再跟一个边界字符。

使用

$replaced = preg_replace('~'+(?='w{1,2}'b)~', '', $yourstring);

  • '+匹配文字+
  • 前瞻(?='w{1,2}'b)断言后面是一个或两个单词字符,然后是一个单词边界
  • 用空字符串
  • 替换

{1,2}是因为你想要最多3个字符的字符串,包括+

仅从长度为1 - 3个字符的单词中删除+,包括+

尝试下面的regex使用捕获组并替换为$1

'+('b'w{1,2}'b)

下面是regex101

的演示

描述:

'b          assert position at a word boundary 
'w{1,2}     match any word character [a-zA-Z0-9_] between 1 and 2 times

模式查找+号后面跟着1和2个字符的长单词。

注意:如果你只是在寻找字母,那么使用[a-z]而不是'w


示例代码:

$re = "/'+('b'w{1,2}'b)/";
$str = "+a +ab +string +of +words +with +different +lengths";
$subst = '$1';
$result = preg_replace($re, $subst, $str);
输出:

a ab +string of +words +with +different +lengths