Php 在不使用preg_*函数的情况下,重建字符串中可能重复的字符的第一个实例的更好方法
我使用的函数需要检测角色的第一个实例,如果角色是重复的,则重构重复的子字符串。例如:Php 在不使用preg_*函数的情况下,重建字符串中可能重复的字符的第一个实例的更好方法,php,repeat,Php,Repeat,我使用的函数需要检测角色的第一个实例,如果角色是重复的,则重构重复的子字符串。例如: $x = 'fhdfhbc::::dcdcdcuttr482rdvcjv:ducvdk:::chjvdbj'; // ---> function should extract :::: 我不想使用任何preg.*函数,因为我尽可能避免使用这些函数(因为这些函数很慢)。我目前的解决方案是: $char = ":"; // this would be set as necessary $char_subs
$x = 'fhdfhbc::::dcdcdcuttr482rdvcjv:ducvdk:::chjvdbj'; // ---> function should extract ::::
我不想使用任何preg.*
函数,因为我尽可能避免使用这些函数(因为这些函数很慢)。我目前的解决方案是:
$char = ":"; // this would be set as necessary
$char_substring = str_repeat($char, strspn(strstr($x, $char), $char)); // yields ---> ::::
注意:此处不能使用strrpos
,因为(在本例中)字符串的另一端可能有冒号。您可以使用explode
,然后运行for
或foreach
循环,在空的部分串联,或此循环的某些变体:
$explode = explode($char, $x);
$substring = $char; // explode array should have 1 less empty member than the repeated character, so need to start with char count of 1
$emptyEncountered = false;
for($i = 0, $count = count($explode); $i < $count; $i++) {
if ($explode[$i]) {
if ($emptyEncountered) break;
} else {
$emptyEncountered = true;
$substring .= $char;
}
}
echo $substring; // ---> ::::
$explode=explode($char,$x);
$substring=$char;//分解数组的空成员应该比重复字符少1个,因此需要以字符数1开始
$emptyEncountered=false;
对于($i=0,$count=count($explode);$i<$count;$i++){
如果($explode[$i]){
如果($EmptyEncounted)中断;
}否则{
$emptyEncountered=true;
$substring.=$char;
}
}
echo$substring;//-->::
有没有比使用preg_*、for/each循环或str_repeat(strspn(strstrstr())更好的方法?正确的
preg_*
实现不仅在时间上,而且在内存消耗和所需分配方面都将优于您的explode
方法
我能想到的唯一有效且符合您的约束条件的实现是while
循环:
$substring = '';
$i = strpos($haystack, $needle);
do {
$substring .= $needle;
++$i;
}
while (isset($haystack{$i}) && $haystack{$i} === $needle);
return $substring;
但是,您自己已经拥有了最高效的实现:
return str_repeat($needle, strspn(strstr($haystack, $needle), $needle));
它在本质上也是很好的功能
您的实现缺少错误处理,我的while
实现也缺少错误处理。在我看来,添加它是绝对必要的,但我忽略了它,因为你确实需要
使用Win 10 PHP TS x64 7.1在我的i7机器上的结果:
$ bench 10000
0.0040609836578369 # str_repeat
0.0044500827789307 # preg_match
0.0046060085296631 # while
0.0050818920135498 # for
0.0052239894866943 # preg_match + preg_quote
0.0079050064086914 # explode
#/usr/bin/env-php
一个适当的preg.*
实现不仅在时间上,而且在内存消耗和所需分配方面,都将胜过您的explode
方法
我能想到的唯一有效且符合您的约束条件的实现是while
循环:
$substring = '';
$i = strpos($haystack, $needle);
do {
$substring .= $needle;
++$i;
}
while (isset($haystack{$i}) && $haystack{$i} === $needle);
return $substring;
但是,您自己已经拥有了最高效的实现:
return str_repeat($needle, strspn(strstr($haystack, $needle), $needle));
它在本质上也是很好的功能
您的实现缺少错误处理,我的while
实现也缺少错误处理。在我看来,添加它是绝对必要的,但我忽略了它,因为你确实需要
使用Win 10 PHP TS x64 7.1在我的i7机器上的结果:
$ bench 10000
0.0040609836578369 # str_repeat
0.0044500827789307 # preg_match
0.0046060085296631 # while
0.0050818920135498 # for
0.0052239894866943 # preg_match + preg_quote
0.0079050064086914 # explode
#/usr/bin/env-php