将字符串转换为不同字符发生的数组 [英] Convert string to array at different character occurence
问题描述
考虑我有这个字符串'aaaabbbaaaaaabbbb'
我想将其转换为数组,以便获得以下结果
Consider I have this string 'aaaabbbaaaaaabbbb'
I want to convert this to array so that I get the following result
$array = [
'aaaa',
'bbb',
'aaaaaa',
'bbbb'
]
如何在PHP中执行此操作?
How to go about this in PHP?
推荐答案
我已经写了一行只使用 preg_split()生成预期的结果,没有浪费的内存(没有阵列膨胀):
I have written a one-liner using only preg_split() that generates the expected result with no wasted memory (no array bloat):
代码(演示):
$string='aaaabbbaaaaaabbbb';
var_export(preg_split('/(.)\1*\K/',$string,NULL,PREG_SPLIT_NO_EMPTY));
输出:
array (
0 => 'aaaa',
1 => 'bbb',
2 => 'aaaaaa',
3 => 'bbbb',
)
模式:
(.) #match any single character
\1* #match the same character zero or more times
\K #keep what is matched so far out of the overall regex match
真正的魔法发生在 \K
,如需更多阅读,请此处。
preg_split()
中的 NULL
参数表示无限制匹配。这是默认行为,但它需要在函数中保留它的位置,以便下一个参数被适当地用作标志
最后一个参数是 PREG_SPLIT_NO_EMPTY
可以删除任何空的匹配。
The real magic happens with the \K
, for more reading go here.
The NULL
parameter in preg_split()
means "unlimited matches". This is the default behavior but it needs to hold its place in the function so that the next parameter is used appropriately as a flag
The final parameter is PREG_SPLIT_NO_EMPTY
which removes any empty matches.
Sahil的 preg_match_all()方法 preg_match_all('/(。)\\ \\ 1 {1,} /',$ string,$ matches);
是一个很好的尝试,但由于两个原因而不完美:
Sahil's preg_match_all() method preg_match_all('/(.)\1{1,}/', $string,$matches);
is a good attempt but it is not perfect for two reasons:
第一个问题是他使用 preg_match_all()
返回两个子阵列,这是必要结果的两倍。
The first issue is that his use of preg_match_all()
returns two subarrays which is double the necessary result.
当 $ string =abbbaaaaaabbb;
时,会显示第二个问题。他的方法将忽略第一个孤单的角色。这是它的输出:
The second issue is revealed when $string="abbbaaaaaabbbb";
. His method will ignore the first lone character. Here is its output:
Array (
[0] => Array
(
[0] => bbb
[1] => aaaaaa
[2] => bbbb
)
[1] => Array
(
[0] => b
[1] => a
[2] => b
)
)
Sahil的第二个尝试产生正确的输出,但需要更多的代码。一个更简洁的非正则表达式解决方案可能如下所示:
Sahil's second attempt produces the correct output, but requires much more code. A more concise non-regex solution could look like this:
$array=str_split($string);
$last="";
foreach($array as $v){
if(!$last || strpos($last,$v)!==false){
$last.=$v;
}else{
$result[]=$last;
$last=$v;
}
}
$result[]=$last;
var_export($result);
这篇关于将字符串转换为不同字符发生的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!