doueta6642 2011-11-23 17:34 采纳率: 0%
浏览 12
已采纳

str_repeat反向(收缩字符串)

str_repeat(A, B) repeat string A, B times:

$string = "This is a " . str_repeat("test", 2) . 
          "! " . str_repeat("hello", 3) . " and Bye!";  

// Return "This is a testtest! hellohellohello and Bye!"

I need reverse operation:

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!"

Best and efficient way for create str_shrink function?

  • 写回答

4条回答 默认 最新

  • duanbi1888 2011-11-23 18:00
    关注

    Here are two versions that I could come up with.

    The first uses a regular expression and replaces duplicate matches of the $needle string with a single $needle string. This is the most vigorously tested version and handles all possibilities of inputs successfully (as far as I know).

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

    The second uses string manipulation to continually replace occurrences of the $needle concatenated with itself. Note that this one will fail if $needle.$needle occurs more than once in the input string (The first one does not have this problem).

    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

    Edit: I didn't realize that the desired output wanted to include the number of repetitions. I've modified my examples accordingly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作