Reputation: 2245
I have a fragment in text like
;flat
CID_999999 = 99999999
CID_999999 = 99999999
CID_999999 = 99999999
CID_999999 = 99999999
where 999999 are some numbers. I want to find this fragment by regexp. When I use this regex:
preg_replace('/;flat[\s\r\n]+[CID_0-9]+\s=\s[0-9]+\n/','REPLACEMENT',$content);
it replaces ;flat
and first CID
string.
So, I suppose that if I put [CID_0-9]+\s=\s[0-9]+\n
part in character class []+
it will remove all CID
strings. But if I do it it doesn't replace anything. So I don't understand something in regex. What am I doing wrong?
I thought that expected output is clear, but ok. I should replace all fragment by REPLACEMENT.
Upvotes: 0
Views: 57
Reputation: 44831
You don't need a character class ([...]
); you need a group ((...)
). Your code should look like this:
preg_replace('/;flat[\s\r\n]+([CID_0-9]+\s=\s[0-9]+\n?)+/', 'REPLACEMENT', $content);
Note the ?
at the end, just in case your last line isn't terminated with a new line (\n
) character.
Upvotes: 0
Reputation: 67968
;flat\s*|(?!^)\G(CID_\d+\s*=\s*\d+\s*)
Try this.Replace by $1
.See demo.
https://regex101.com/r/gQ3kS4/7
$re = "/;flat\\s*|(?!^)\\G(CID_\\d+\\s*=\\s*\\d+\\s*)/";
$str = ";flat\nCID_999999 = 99999999\nCID_999999 = 99999999\nCID_999999 = 99999999\nCID_999999 = 99999999\n;";
$subst = "$1";
$result = preg_replace($re, $subst, $str);
Upvotes: 0
Reputation: 9522
Use lookbehind if you are trying to match just the digits after the =
and before the newline
For more accurate matching use CID[0-9]+
rather than [CID0-9]+
preg_replace('/(?<;flat[\s\r\n]+CID_[0-9]+\s=\s)[0-9]+(?=\n)/','REPLACEMENT',$content);
Upvotes: 1