How to use mb_substr() with while loop In PHP
Using mb_substr() with a while loop in PHP involves determining the string length with mb_strlen() and iterating through each character using mb_substr(), ensuring correct handling of multi-byte characters for accurate iteration.
Syntax:
while ($i < $len) {
$char = mb_substr($str, $i, 1, 'UTF-8');
echo $char . "\n";
$i++;
}
Example:
<?php
$str = "w3wiki";
$len = mb_strlen($str, 'UTF-8');
$i = 0;
while ($i < $len) {
$char = mb_substr($str, $i, 1, 'UTF-8');
echo $char . "\n";
$i++;
}
?>
Output:
G
e
e
k
s
f
o
r
G
e
e
k
s
How to Iterate Over Characters of a String in PHP ?
This article will show you how to iterate over characters of string in PHP. It means how to loop through an array of characters in a string. There are two methods to iterate over the character of a string, these are:
Table of Content
- Using str_split() function and foreach Loop
- Using for Loop
- Using mb_substr() with while loop
Contact Us