PHP - 迭代字符串字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4601032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - iterate on string characters
提问by jon_darkstar
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.
有没有一种很好的方法来迭代字符串的字符?我希望能够做到foreach
,array_map
,array_walk
,array_filter
在字符串中的字符等。
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?
类型转换/杂耍并没有让我在任何地方(将整个字符串作为数组的一个元素),我发现的最佳解决方案只是使用 for 循环来构造数组。感觉应该有更好的东西。我的意思是,如果你可以索引它,你不应该也可以迭代吗?
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?)
A)使字符串可迭代的方法
B)从字符串构建字符数组的更好方法(如果是,另一个方向怎么样?)
I feel like im missing something obvious here.
我觉得我在这里遗漏了一些明显的东西。
回答by SeaBrightSystems
Step 1:convert the string to an array using the str_split
function
步骤 1:使用str_split
函数将字符串转换为数组
$array = str_split($your_string);
$array = str_split($your_string);
Step 2:loop through the newly created array
第 2 步:遍历新创建的数组
foreach ($array as $char) {
echo $char;
}
You can check the PHP docs for more information: str_split
您可以查看 PHP 文档以获取更多信息: str_split
回答by Owen
Iterate string:
迭代字符串:
for ($i = 0; $i < strlen($str); $i++){
echo $str[$i];
}
回答by Dawid Ohia
If your strings are in Unicode you should use preg_split
with /u
modifier
如果你的字符串是用Unicode,你应该使用preg_split
与/u
修改
From comments in php documentation:
来自 php 文档中的评论:
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
回答by Moritur
You can also just access $s1 like an array, if you only need to access it:
如果您只需要访问它,您也可以像访问数组一样访问 $s1:
$s1 = "hello world";
echo $s1[0]; // -> h
回答by Dairy Window
Expanded from @SeaBrightSystems answer, you could try this:
从@SeaBrightSystems 答案扩展,你可以试试这个:
$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array
回答by AmirHossein
For those who are looking for the fastest way to iterate over strings in php, Ive prepared a benchmark testing.
The first method in which you access string characters directly by specifying its position in brackets and treating string like an array:
对于那些正在寻找在 php 中迭代字符串的最快方法的人,我准备了一个基准测试。
第一种方法是通过在括号中指定其位置并将字符串视为数组来直接访问字符串字符:
$string = "a sample string for testing";
$char = $string[4] // equals to m
I myself thought the latter is the fastest method, but I was wrong.
As with the second method (which is used in the accepted answer):
我自己认为后者是最快的方法,但我错了。
与第二种方法(在接受的答案中使用)一样:
$string = "a sample string for testing";
$string = str_split($string);
$char = $string[4] // equals to m
This method is going to be faster cause we are using a realarray and not assuming one to be an array.
这种方法会更快,因为我们使用的是一个真正的数组,而不是假设一个数组是一个数组。
Calling the last line of each of the above methods for 1000000
times lead to these benchmarking results:
1000000
多次调用上述每个方法的最后一行会导致这些基准测试结果:
Using string[i]0.24960017204285 Seconds
使用字符串[i]0.24960017204285 Seconds
Using str_split0.18720006942749 Seconds
使用 str_split0.18720006942749 Seconds
Which means the second method is way faster.
这意味着第二种方法要快得多。
回答by Ash
Hmm... There's no need to complicate things. The basics work great always.
嗯……没必要把事情复杂化。基础工作总是很好。
$string = 'abcdef';
$len = strlen( $string );
$x = 0;
Forward Direction:
前进方向:
while ( $len > $x ) echo $string[ $x++ ];
Outputs: abcdef
输出: abcdef
Reverse Direction:
反向:
while ( $len ) echo $string[ --$len ];
Outputs: fedcba
输出: fedcba
回答by masakielastic
// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";
// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
yield mb_substr($str, $i, 1);
}
})($str);
var_dump(
true === $gen instanceof Traversable,
// PHP 7.1
true === is_iterable($gen)
);
foreach ($gen as $char) {
echo $char, PHP_EOL;
}
回答by Accountant ?
Most of the answers forgot about non English characters !!!
大多数答案都忘记了非英文字符!!!
strlen
counts BYTES, not characters, that is why it is and it's sibling functions works fine with English characters, because English characters are stored in 1 byte in both UTF-8 and ASCII encodings, you need to use the multibyte string functionsmb_*
strlen
计数字节,而不是字符,这就是为什么它是,它的兄弟函数适用于英文字符,因为英文字符在 UTF-8 和 ASCII 编码中都存储在 1 个字节中,您需要使用多字节字符串函数mb_*
This will work with anycharacter encoded in UTF-8
这将适用于任何编码的字符UTF-8
// 8 characters in 12 bytes
$string = "abcd????";
$charsCount = mb_strlen($string, 'UTF-8');
for($i = 0; $i < $charsCount; $i++){
$char = mb_substr($string, $i, 1, 'UTF-8');
var_dump($char);
}
This outputs
这输出
string(1) "a"
string(1) "b"
string(1) "c"
string(1) "d"
string(2) "?"
string(2) "?"
string(2) "?"
string(2) "?"