PHP - 在字符串中的字符迭代 [英] PHP - iterate on string characters
问题描述
有没有遍历一个字符串的字符的好方法?我希望能够做到的foreach
, array_map
, array_walk
, array_filter
等在字符串中的字符。
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.
类型转换/杂耍没有得到我在任何地方(把整个字符串作为数组的一个元素),我已经找到了最好的解决方案是简单地使用一个for循环来构建阵列。这感觉就像应该有更好的东西。我的意思是,如果你可以在它的索引应该不是你能重复呢?
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?
这是我已经得到了最好
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);
有两种:
A)的方式,使该字符串可迭代的结果
B)一个更好的方式来建立从字符串的字符数组(如果有的话,怎么样另一个方向?)
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?)
我觉得像IM缺少明显的东西在这里。
I feel like im missing something obvious here.
推荐答案
什么 str_split
?
这篇关于PHP - 在字符串中的字符迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!