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

后端 未结 4 1644
无人及你
无人及你 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 09:11

    Your regex .{170}\S*\s is fine but has a little problem. It doesn't guarantee if \S* matches rest of a word as it may match an MD5 - 170 characters up to first character of MD5 hash then matching 31 more characters which could be more than this.

    You are treating those 170 characters as a delimiter of preg_split, hence you didn't have it in output.

    Considering these two things in mind, you may come with a better idea:

    $array = preg_split('~^[\s\S]{1,170}+(?(?!\S{10,})\S*)\K~', $string);
    

    PHP live demo

    10 ensures there is no non-whitespace characters more than that. If exists it splits right after 170 characters.

    Accessing to $array[0] you could add your read more text to it.

提交回复
热议问题