简体   繁体   中英

Regex replace one or two letter words

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.

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)

Just use:

echo preg_replace('/(?<!\S)\S{1,2}(?!\S)/i', '', 'a dljlj-b2 adl xy zq a');

The output is as wanted:

 dljlj-b2 adl  

So don't forget to handle beginning/end of a string by negative assertions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM