PHP - 迭代字符串字符 [英] PHP - iterate on string characters

查看:41
本文介绍了PHP - 迭代字符串字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种很好的方法来迭代字符串的字符?我希望能够对字符进行 foreacharray_maparray_walkarray_filter 等一个字符串.

类型转换/杂耍并没有让我在任何地方(将整个字符串作为数组的一个元素),我发现的最佳解决方案是简单地使用 for 循环来构造数组.感觉应该有更好的东西.我的意思是,如果你可以索引它,你不应该也可以迭代吗?

这是我得到的最好的

function stringToArray($s){$r = 数组();for($i=0; $i

有没有:

A) 一种使字符串可迭代的方法
B) 从字符串构建字符数组的更好方法(如果是,另一个方向如何?)

我觉得我在这里遗漏了一些明显的东西.

解决方案

第一步:使用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

这篇关于PHP - 迭代字符串字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆