str_repeat(A, B) 重复字符串 A、B 次:
$string = "This is a " . str_repeat("test", 2) .
"! " . str_repeat("hello", 3) . " and Bye!";
// Return "This is a testtest! hellohellohello and Bye!"
我需要反向操作:
str_shrink($string, array("hello", "test"));
// Return "This is a test(x2)! hello(x3) and Bye!" or
// "This is a [test]x2! [hello]x3 and Bye!"
创建 str_shrink 函数的最佳且有效的方法?
最佳答案
这是我可以想到的两个版本。
第一个使用正则表达式,并将 $needle
字符串的重复匹配项替换为单个 $needle
字符串。这是经过最严格测试的版本,可以成功处理所有可能的输入(据我所知)。
function str_shrink( $str, $needle)
{
if( is_array( $needle))
{
foreach( $needle as $n)
{
$str = str_shrink( $str, $n);
}
return $str;
}
$regex = '/(' . $needle . ')(?:' . $needle . ')+/i';
return preg_replace_callback( $regex, function( $matches) { return $matches[1] . '(x' . substr_count( $matches[0], $matches[1]) . ')'; }, $str);
}
第二个使用字符串操作来不断替换与其自身连接的 $needle
的出现。请注意,如果 $needle.$needle
在输入字符串中出现多次,此操作将会失败(第一个没有此问题)。
function str_shrink2( $str, $needle)
{
if( is_array( $needle))
{
foreach( $needle as $n)
{
$str = str_shrink2( $str, $n);
}
return $str;
}
$count = 1; $previous = -1;
while( ($i = strpos( $str, $needle.$needle)) > 0)
{
$str = str_replace( $needle.$needle, $needle, $str);
$count++;
$previous = $i;
}
if( $count > 1)
{
$str = substr( $str, 0, $previous) . $needle .'(x' . $count . ')' . substr( $str, $previous + strlen( $needle));
}
return $str;
}
编辑:我没有意识到所需的输出想要包含重复次数。我相应地修改了我的示例。
关于php - str_repeat 反向(收缩字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246588/