How to intercept and replace by word count in php

藏色散人
Release: 2023-03-12 09:12:01
Original
1822 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!