Home >Backend Development >PHP Problem >How to intercept and replace by word count in php

How to intercept and replace by word count in php

藏色散人
藏色散人Original
2021-09-01 10:14:241898browse

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.

How to intercept and replace by word count in php

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, &#39;UTF-8&#39;)<=$len)
{
return $str;
}
// 截取
$i = 0;
$tlen = 0;
$tstr = &#39;&#39;;
while ($tlen < $len)
{
$chr = mb_substr($str, $i, 1, &#39;UTF-8&#39;);
$chrLen = ord($chr) > 127 ? 2 : 1;
if ($tlen + $chrLen > $len) break;
$tstr .= $chr;
$tlen += $chrLen;
$i ++;
}
if ($tstr != $str)
{
$tstr .= &#39;...&#39;;
}
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn