How to add an ellipsis hyperlink after the first space beyond 170 characters?

后端 未结 4 1643
无人及你
无人及你 2021-01-26 08:44

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         


        
4条回答
  •  灰色年华
    2021-01-26 08:52

    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 by pattern, or FALSE 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.

提交回复
热议问题