Basically my preg_match is working fine. However when only a partial value of the text (not digits) exist, I need to know an attempt was tried to enter the right thing.
Example 1:
$text = "2000 FC
2 A
100 FH
1200 ACT FC
";
Example 2:
$text = "2000 FC
2 A
100 FH
ACT FC
";
CODE:
preg_match("~(?P<value>\d+(?:.\d+)*?)\h(?P<unit>ACT\sFC)~", $text, $act_fc);
Example 1 is showing the correct text "1200 ACT FC". When preg_match is executed 1200 is assigned to value and ACT_FC is assigned to unit in the $act_fc array.
However if there is a case like Example 2 with "ACT FC" only, then $act_fc array is empty.
Without doing another preg_match to check only for "ACT FC", is there a way to return ACT_FC was found? Maybe "unit" could be forced to populate the array and "value" could be null.
NOTE: I am dealing with matching data between newlines, so that part of the code is important to stay nearly the same.
You can make the value part optional with (?:...)?
:
preg_match("/(?:(?P<value>\d+(?:\.\d+)*?)\h)?(?P<unit>ACT\sFC)/", $text, $act_fc);
Here is demo. And here is regex tester.