Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replace one or two letter words

Tags:

regex

php

I am trying to replace one or two letters in a string. Please consider this regex

$str = 'I haven\'t got much time to spend!';
echo preg_replace('/\b([a-z0-9]{1,2})\b/i','',$str);

returns: haven' got much time spend!
expected output: haven't got much time spend!

My goal is remove any one or two characters length words from a string. This can be alphanumeric or special characters.

like image 237
Maximus Avatar asked Oct 16 '25 04:10

Maximus


1 Answers

Use lookarounds:

preg_replace('/(?<!\S)\S{1,2}(?!\S)/', '', $str)

Altho this leaves double whitespace when words are removed. To also remove spaces you could try something like:

preg_replace('/\s+\S{1,2}(?!\S)|(?<!\S)\S{1,2}\s+/', '', $str)
like image 183
Qtax Avatar answered Oct 18 '25 16:10

Qtax