John Davidson

Regex in php excluding values


I have these lines of text ($text variable)

CC 1,00
SS 1,00
PP 1,00
FF 1,00

now I would like to have only the numeric part of each line returned to me. But the important thing must be that I don't have to take lines that start with certain characters, like I would like to exclude "SS", "PP" and "FF".
So I would like it to return me only the values of "CC" and only the numeric ones without leading characters.

In the meantime I have done this but it doesn't seem to work

preg_match_all("/((?!.SS|.FF|.PP).*\d{1,2}[\,\.]{1}\d{1,2})\w+/", $text, $matches);

Unfortunately, I don't get the desired result, where am I wrong?

My Answer:
You can use the following regex pattern in PHP to exclude lines that start with certain characters and extract only the numeric part of each line:

$text = "_CC 1,00_SS 1,00_PP 1,00_1,00_FF 1,00_";

$pattern = '/^(?!_CC|_SS|_PP|_FF).*?(\d+(?:,\d+)?)/m';

preg_match_all($pattern, $text, $matches);

$numericValues = $matches[1];


This code will output:

[0] => 1,00
[1] => 1,00
[2] => 1,00
[3] => 1,00

This regex pattern uses a negative lookahead `(?!_CC|_SS|_PP|_FF)` to exclude lines that start with `_CC`, `_SS`, `_PP`, or `_FF`. The `(\d+(?:,\d+)?)` part of the pattern captures the numeric part of each line. The `m` flag is used to make the regex match each line separately.

Rate this post

3 of 5 based on 4469 votes


© 2024 - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us