PHP - Check if string contains words longer than 4 characters, then include "+ *", and for those shorter than 4 characters include only "*"



PHP Snippet 1:

$string = "This is a short sentence which should include all regex results";
echo preg_replace(array('/\b(\w{1,3})\b/', '/\b(\w{4,})\b/'), array('$1*', '+$1*'), $string);

PHP Snippet 2:

+This* is* a* +short* +sentence* +which* +should* +include* all* +regex* +results*

PHP Snippet 3:

$string = "This is a short sentence which should include all regex results";
echo preg_replace_callback(
         '~(\w{3})?(\w+)~',
         fn($m) => ($m[1] ? "+" : '') . "$m[0]*",
         $string
     );

PHP Snippet 4:

+This* is* a* +short* +sentence* +which* +should* +include* all* +regex* +results*