php - str_repeat 反向(收缩字符串)

标签 php string

str_repeat(A, B) 重复字符串 AB 次:

$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;
}

See them both in action

编辑:我没有意识到所需的输出想要包含重复次数。我相应地修改了我的示例。

关于php - str_repeat 反向(收缩字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246588/

相关文章:

java - 使用Character.isLetter和Character.isDigit忽略数字、空格并读取字符串输入

php - 使用高级php上传图片

php - PHP 中的 $x+++$X++ 是什么? increment 的异常使用

php - MySQL 正则表达式在 php 脚本中失败

java - 将字符串转换为java类型

Java:将固定大小的字节数组转换为可变长度的字符串

php - 执行此 PHP/SQL/Sort 操作的最快方法是什么

java - 计算平均值的简单数学公式

string - 如何通过静态方法在 clojure 中进行 comp ?

Javascript Regexp - 替换函数应该决定不替换匹配的字符串,以让其他带括号的子匹配字符串与匹配一起使用