w3resource

PHP: chunk_split() function

Description

The chunk_split() function is used to split a string into a series of smaller chunks.

Version:

(PHP 4 and above)

Syntax:

chunk_split(string_name, string_length, end_string) 

Parameters:

Name Description Required /
Optional
Type
string_name The string to be split. Required String
string_length The chunk length. Optional Integer
end_string The line ending sequence. Optional String

Return values

The extracted string.

Value Type: String.

Pictorial Presentation

php-string-chunk_split()

Example:

<?php
$string_name1='w3resource.com';
echo chunk_split($string_name1,1,".");
echo '<br>';
echo chunk_split($string_name1,2,"/");
echo '<br>';
echo chunk_split($string_name1,1,"--");
?>

Output:

w.3.r.e.s.o.u.r.c.e...c.o.m.
w3/re/so/ur/ce/.c/om/
w--3--r--e--s--o--u--r--c--e--.--c--o--m--

View the example in the browser

See also

PHP Function Reference

Previous: chr
Next: convert_cyr_string



PHP: Tips of the Day

PHP: Using str_replace so that it only acts on the first match?

Can be done with preg_replace:

function str_replace_first($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);
}

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

Ref : https://bit.ly/35SCuP8