I have a long text like below:
$postText=\"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its l
split array always return the first index as null.
It doesn't return NULL, it returns an empty string (''
); they are completely different objects with different semantics.
The reason why the first element of the returned array is an empty string is clearly documented in the manual page of preg_split():
Return Values:
Returns an array containing substrings of
subject
split along boundaries matched bypattern
, orFALSE
on failure.
The regex you provide as the first argument to preg_split() is used to match the delimiter, not the pieces. The function you need is preg_match():
$postText = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.";
preg_match('/^.{170}\S*/', $postText, $matches);
$postText = $matches[0] . " ...read more";
If preg_match()
returns TRUE
, $matches[0]
contains the string you need.
There are situations when preg_match()
fails with your original regex
. For example, if your input string has exactly 170 characters, the \s
won't match. This is why I removed the \s
from the regex
and added a white space in front of the string appended after the match.