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?
Here are two versions that I could come up with.
The first uses a regular expression and replaces duplicate matches of the
$needlestring with a single$needlestring. This is the most vigorously tested version and handles all possibilities of inputs successfully (as far as I know).The second uses string manipulation to continually replace occurrences of the
$needleconcatenated with itself. Note that this one will fail if$needle.$needleoccurs more than once in the input string (The first one does not have this problem).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.