且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP - 迭代字符串字符

更新时间:2023-02-23 08:53:31

第一步:使用str_split函数将字符串转换为数组

$array = str_split($your_string);

第 2 步:循环遍历新创建的数组

foreach ($array as $char) {回声 $char;}

您可以查看 PHP 文档了解更多信息:str_split>

Is there a nice way to iterate on the characters of a string? I'd like to be able to do foreach, array_map, array_walk, array_filter etc. on the characters of a string.

Type casting/juggling didnt get me anywhere (put the whole string as one element of array), and the best solution I've found is simply using a for loop to construct the array. It feels like there should be something better. I mean, if you can index on it shouldn't you be able to iterate as well?

This is the best I've got

function stringToArray($s)
{
    $r = array();
    for($i=0; $i<strlen($s); $i++) 
         $r[$i] = $s[$i];
    return $r;
}

$s1 = "textasstringwoohoo";
$arr = stringToArray($s1); //$arr now has character array

$ascval = array_map('ord', $arr);  //so i can do stuff like this
$foreach ($arr as $curChar) {....}
$evenAsciiOnly = array_filter( function($x) {return ord($x) % 2 === 0;}, $arr);

Is there either:

A) A way to make the string iterable
B) A better way to build the character array from the string (and if so, how about the other direction?)

I feel like im missing something obvious here.

Step 1: convert the string to an array using the str_split function

$array = str_split($your_string);

Step 2: loop through the newly created array

foreach ($array as $char) {
 echo $char;
}

You can check the PHP docs for more information: str_split