Hi guys,

I'm looking for a way to repeat part of a string X times. I will have markers to say which part of the string to repeat e.g. $str = "this is a string and I want to repeat repeat((this part)) and repeat((this part)) X number of times"; How could I do this?

TIA

    You can do that with regexes. Take a look at preg_replace() in the php manual. Specifically what you will want to do is use a replacement with a reference to the matched pattern (e.g. $1 $1 $1 $1 to repeat 4 times).

      <?php
      function repeat($text, $numRepeats)
      {
         if(!function_exists('repeat_repeat'))
         {
            function repeat_repeat($txt, $rpt)
            {
               $out = "";
               for($i=0; $i<$rpt; $i++)
               {
                  $out .= $txt . ' ';
               }
               return $out;
            }
         }
         $search = '/__repeat\(\((.+)\)\)/Use';
         $replace = "repeat_repeat('$1', $numRepeats)";
         return preg_replace($search, $replace, $text);
      }
      // TEST
      $str = "this is a string and I want to repeat __repeat((this part)) and __repeat((this part)) X number of times";
      echo repeat($str, 3);
      

        Hi, thank guys. I've worked out a solution using a loop and substr with strpos. THanks for the other suggestions anyway.

          Write a Reply...