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
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)
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.