Home >Backend Development >PHP Problem >How to intercept and replace by word count in php
php method to intercept and replace by word count: 1. Use the "function substr_format(){...}" method to intercept and replace; 2. Use "function cut_string($str, $len){... }" method to intercept and replace.
The operating environment of this article: Windows7 system, PHP7.1 version, Dell G3 computer
How to intercept and replace php according to the number of words?
PHP intercepts a string of specified length, and replaces the excess part with ..
function substr_format($text, $length, $replace='..', $encoding='UTF-8') { if ($text && mb_strlen($text, $encoding)>$length) { return mb_substr($text, 0, $length, $encoding).$replace; } return $text; }
and
function cut_string($str, $len) { // 检查长度 if (mb_strwidth($str, 'UTF-8')<=$len) { return $str; } // 截取 $i = 0; $tlen = 0; $tstr = ''; while ($tlen < $len) { $chr = mb_substr($str, $i, 1, 'UTF-8'); $chrLen = ord($chr) > 127 ? 2 : 1; if ($tlen + $chrLen > $len) break; $tstr .= $chr; $tlen += $chrLen; $i ++; } if ($tstr != $str) { $tstr .= '...'; } return $tstr; }
Recommended: "PHP Video Tutorial》
The above is the detailed content of How to intercept and replace by word count in php. For more information, please follow other related articles on the PHP Chinese website!