PHP splits a string into a series of smaller parts using the chunk_split() function

黄舟
Release: 2023-03-16 21:44:01
Original
2038 people have browsed it

Example

Split the string once after each characterString, and add "." after each split:

<?php
$str = "Hello world!";
echo chunk_split($str,1,".");
?>
Copy after login

Definition and usage

chunk_split() function splits a string into a series of smaller parts.

Note: This function does not change the original string.

Syntax

chunk_split(string,length,end)
Copy after login
ParametersDescription
string Required. Specifies the string to be split.
length Optional. A number defining the length of the string block. Default is 76.
endOptional. A string defining what is placed after each string block. Default is \r\n.

Technical details

Return value: Returns the split string.
PHP version: 4+
##More examples

Example 1

Split the string after every six characters, and add "..." after each split:

<?php
$str = "Hello world!";
echo chunk_split($str,6,"...");
?>
Copy after login

Example: Support wide character splitting, (Split the string into a series of smaller parts)

<?php  
/** 
 * 分割字符串  
 * @param String $str  要分割的字符串  
 * @param int $length  指定的长度  
 * @param String $end  在分割后的字符串块追加的内容  
 */  
function mb_chunk_split($string, $length, $end, $once = false){  
    $string = iconv(&#39;gb2312&#39;, &#39;utf-8//ignore&#39;, $string);  
    $array = array();  
    $strlen = mb_strlen($string);  
    while($strlen){  
        $array[] = mb_substr($string, 0, $length, "utf-8");  
        if($once)  
            return $array[0] . $end;  
        $string = mb_substr($string, $length, $strlen, "utf-8");  
        $strlen = mb_strlen($string);  
    }  
    return implode($end, $array);  
}   
  
$str = &#39;s六一马上$就dfs要到$@#了&#39;;  
$str1 = &#39;aabbccddeefff&#39;;  
echo mb_chunk_split($str, 3, &#39;...&#39;, true); //s六一...马上$...就df...s要到...$@#...了    
echo "<br>";  
echo mb_chunk_split($str1, 2, &#39;...&#39;); //aa...bb...cc...dd...ee...ff...f
Copy after login

The above is the detailed content of PHP splits a string into a series of smaller parts using the chunk_split() function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!