I would like to how can I remove long word from a string. Words greater than length n.
I tried the following:
//remove words which have more than 5 characters from string
$s = 'abba bbbbbbbbbbbb 1234567 zxcee ytytytytytytytyt zczc xyz';
echo preg_replace("~\s(.{5,})\s~isU", " ", $s);
Gives the Output (which is incorrect):
abba 1234567 ytytytytytytytyt zczc xyz
Use this regex: \b\w{5,}\b
. It will match long words.
\b
- word boundary\w{5,}
- alphanumeric 5
or more repetitions\b
- word boundary<?php
//remove words which have more than 5 characters from string
$s = 'abba bbbbbbbbbbbb 1234567 zxcee ytytytytytytytyt zczc xyz';
$patterns = array(
'long_words' => '/[^\s]{5,}/',
'multiple_spaces' => '/\s{2,}/'
);
$replacements = array(
'long_words' => '',
'multiple_spaces' => ' '
);
echo trim(preg_replace($patterns, $replacements, $s));
?>
Output:
abba zczc xyz
Update, to address the issue you presented in the comments. You can do it like this:
<?php
//remove words which have more than 5 characters from string
$s = '123 ReallyLongStringComesHere 123';
$patterns = array(
'html_space' => '/ /',
'long_words' => '/[^\s]{5,}/',
'multiple_spaces' => '/\s{2,}/'
);
$replacements = array(
'html_space' => ' ',
'long_words' => '',
'multiple_spaces' => ' '
);
echo str_replace(' ', ' ', trim(preg_replace($patterns, $replacements, $s)));
?>
Output:
123 123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With