PHP - Iterate on String Characters

PHP - iterate on string characters

Use str_split to iterate ASCII strings (since PHP 5.0)

If your string contains only ASCII (i.e. "English") characters, then use str_split.

$str = 'some text';
foreach (str_split($str) as $char) {
var_dump($char);
}

Use mb_str_split to iterate Unicode strings (since PHP 7.4)

If your string might contain Unicode (i.e. "non-English") characters, then you must use mb_str_split.

$str = 'μυρτιὲς δὲν θὰ βρῶ';
foreach (mb_str_split($str) as $char) {
var_dump($char);
}

How to iterate UTF-8 string in PHP?

Use preg_split. With "u" modifier it supports UTF-8 unicode.

$chrArray = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);

How to iterate a string containing cyrillic characters?

You cannot simply use offset numbers to access multibyte characters.

You need to use mb_strlen() AND mb_substr() to isolate your desired substrings.

*note: caching $len is a good idea. mb_ functions are expensive; it is best to minimize the number of times you call them in a script.

Code: (Demo)

$str = "слово";
$temp = "";
for ($i = 0, $len = mb_strlen($str); $i < $len; $i++) {
$temp .= mb_substr($str, $i, 1);
echo $temp . '<br>';
}
echo $temp;

Output:

с<br>сл<br>сло<br>слов<br>слово<br>слово

Depending on what your actual project needs are, here is an alternative that doesn't require a $temp variable:

$str = "слово";
for ($i = 0, $len = mb_strlen($str); $i < $len; $i++) {
if ($i) echo '<br>';
echo mb_substr($str, 0, $i + 1);
}
// с<br>сл<br>сло<br>слов<br>слово

More simply, you can split the string into an array of individual letters and iterate that. Demo

$str = "слово";
$temp = "";
foreach (mb_str_split($str) as $char) {
$temp .= $char;
echo $temp . '<br>';
}
echo $temp;

PHP: Split a string in to an array foreach char

You can access characters in strings in the same way as you would access an array index, e.g.

$length = strlen($string);
$thisWordCodeVerdeeld = array();
for ($i=0; $i<$length; $i++) {
$thisWordCodeVerdeeld[$i] = $string[$i];
}

You could also do:

$thisWordCodeVerdeeld = str_split($string);

However you might find it is easier to validate the string as a whole string, e.g. using regular expressions.

Foreach a string in PHP

$str[$i] doesn't treat it as an array. This is just a shorthand notation for substr($str, $i, 1).

You can use str_split() to get an array of characters from a string:

foreach (str_split($str) as $letter)

From the documentation:

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42].

Why Can't We Use Foreach Loop On The String Like For Loop

Foreach needs array (or object), and string is not "true" array. It is just some help feature, that you can access to chars as in array.

foreach(str_split($str) as $k=>$v)

Getting value in loop and replace it in string once in PHP

Non-regex way:

Make a hashmap of your lang characters and loop your string character by character. If the current character is set in the map, add those span tags, else just append the current character.

<?php

$str = "we are checking it";
$langs = array ('w', 'c', 'i');
$lang_map = array_flip($langs);

$new_str = "";

for($i = 0; $i < strlen($str); ++$i){
if(isset($lang_map[ $str[$i] ])){
$new_str .= "<span style='color:red;'>".$str[$i]."</span>";
}else{
$new_str .= $str[$i];
}
}

echo $new_str;

Online Demo

Regex way:

You can use preg_replace to replace each character from lang surrounded by span tags like below:

<?php

$str = "we are checking it";
$langs = array ('w', 'c', 'i');
$lang_regex = preg_quote(implode("", $langs));

$str = preg_replace("/[$lang_regex]/", "<span style='color:red;'>$0</span>", $str);

echo $str;

Online Demo



Related Topics



Leave a reply



Submit