Sorry for the very basic question, but there’s simply no easy way to search for a string like that nor here neither in Google or SymbolHound. Also haven’t found an answer in PHP Manual (Pattern Syntax & preg_replace).
This code is inside a function that receives the $content and $length parameters.
What does that preg_replace serves for?
$the_string = preg_replace('#\s+#', ' ', $content);
$words = explode(' ', $the_string);
if( count($words) <= $length )
Also, would it be better to use str_word_count instead?
This pattern replaces successive space characters (note, not just spaces, but also line breaks or tabs) with a single, conventional space (‘ ‘).
\s+says “match a sequence, made up of one or more space characters”.The
#signs are delimiters for the pattern. Probably more common is to see patterns delimited by forward slashes. (Actually you can do REGEX in PHP without delimiters but doing so has implications on how the pattern is handled, which is beyond the scope of this question/answer).http://php.net/manual/en/regexp.reference.delimiters.php
Relying on spaces to find words in a string is generally not the best approach – we can use the
\bword boundary marker instead.That says: grab all substrings within the greater string that are comprised of only alphanumeric characters or hyphens, and which are encased by a word boundary.
$wordsis now an array of words used in the sentence.