RegEx Problem with PHP
I would like to use the following regex with PHP to replace all repetitions of a character at the start of a strin开发者_开发知识库g:
^.{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.
Bye, Christian
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")
You've escaped the ^
! Change it to ^.{3,5000}
and it should work.
精彩评论