可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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
回答2:
Iterate string:
for ($i = 0; $i < strlen($str); $i++){
echo $str[$i];
}
回答3:
If your strings are in Unicode you should use preg_split
with /u
modifier
From comments in php documentation:
function mb_str_split( $string ) {
# Split at all position not after the start: ^
# and not before the end: $
return preg_split('/(?<!^)(?!$)/u', $string );
}
回答4:
You can also just access $s1 like an array, if you only need to access it:
$s1 = "hello world";
echo $s1[0]; // -> h
回答5:
Expanded from @SeaBrightSystems answer, you could try this:
$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array
回答6:
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:
$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 real array 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:
Using string[i]
0.24960017204285 Seconds
Using str_split
0.18720006942749 Seconds
Which means the second method is way faster.
回答7:
// 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;
}
回答8:
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
Reverse Direction:
while ( $len ) echo $string[ --$len ];
Outputs: fedcba