user81993
user81993

Reputation: 6613

How to loop through all the characters in a string?

I tried doing it like this:

for ($i = 0; $i < strlen($s); $i++) {
    $char = $s[$i]; 
    ...
}

but it appears to be wrong when characters that don't fit into 1 byte are involved. strlen("ää") returns 4 for example which would suggest they are composed of 2 bytes.

How do I go through each character in php?

Upvotes: 0

Views: 2721

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

Simple one-line "trick" to get set of multibyte characters using preg_split function with /u (utf-8) modifier:

$str = "äänä";
$chars = preg_split("//u", $str, 0, PREG_SPLIT_NO_EMPTY);

print_r($chars);

The output:

Array
(
    [0] => ä
    [1] => ä
    [2] => n
    [3] => ä
)

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212522

That code loops through the bytes in the string, not the characters.... use the mb_* functions for working with multibyte character strings

for ($i = 0; $i < mb_strlen($s); $i++) {
    $char = mb_substr($s, $i, 1);
    ...
}

Upvotes: 5

Related Questions