itsame69
itsame69

Reputation: 1560

Replace consecutively repeated characters at the start of a string with preg_replace()

I would like to use the following regex with PHP to replace all repetitions of a character at the start of a string:

^.{3,5000}

If I use

echo preg_replace('#\^.{3,5000}#i', '', '------This is a test.');

will echo the text "------This is a test." although the regex itself works fine in any regex tester.

Upvotes: 1

Views: 79

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170158

Try this instead:

<?php
echo preg_replace('#^(.)\1{3,5000}#', '', '------This is a test.');
?>

which will print:

This is a test.

as you can see on Ideone.

Note that the parenthesis around . store whatever is matched in group 1. This group 1 is then repeated between 3 and 5000 times. So, in total, it matches a minimum of 4 repeating characters. If you wanted to match at least 3 repeating characters (and an arbitrary amount after that), you could do something like this:

'#^(.)\1{2,}#'

(by omitting the second integer value in {2,} you'll match any amount. In short, {2,} means: "two or more")

Upvotes: 6

Ry-
Ry-

Reputation: 224913

You've escaped the ^! Change it to ^.{3,5000} and it should work.

Upvotes: 0

Related Questions