正则表达式删除字符串中三个或更少字符单词的第一个字符

I have strings like +a +string +of +words +with +different +lengths

I want to use php's preg_replace to remove + only froms words that are 1 - 3 characters long including +. Required output is a +string of +words +with +different +lengths

Without capturing groups,

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

DEMO

Your final PHP code would be,

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

Output:

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

Explanation:

(?<= |^)\+(?=\w{1,3}\b)
  • (?<= |^) Positive lookbehind to look only after the starting point or space.
  • \+ A literal + sign
  • (?=\w{1,3}\b) The characters following the + sign must be (1 to 3) word characters which is again followed by a boundary charaqcter.

remove + only froms words that are 1 - 3 characters long including +

Try below regex using capturing groups and replace with $1

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

Here is demo on regex101

Description:

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

Pattern looks for + sign followed by 1 and 2 characters long word.

Note: If you are looking for only letters then use [a-z] instead of \w.


Sample code:

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

$result = preg_replace($re, $subst, $str);

output:

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

Use this:

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

Explanation

  • \+ match a literal +
  • The lookahead (?=\w{1,2}\b) asserts that what follows are one or two word characters then a word boundary
  • Replace with the empty string

The {1,2} is because you want to target strings of 3 chars at the most including the +