I’ve been working on this for a bit, but my regex is weak.
I need to check to see if a number is a whole number (single digit) and append a “.001” to it if so. The problem is, it’s in the middle of a line with values separated by commas.
MATERIALS,1,1,9999;1 4PL1 PB_Mel,,1,6,0.173,0.173,0.375,0,0.375,0,0,0,0,2,0,1,1
Needs to be
MATERIALS,1,1,9999;1 4PL1 PB_Mel,,1.001,6,0.173,0.173,0.375,0,0.375,0,0,0,0,2,0,1,1
- The line must start with “MATERIALS”.
- There are more than one MATERIALS lines.
- The value will always be after 5 commas.
I was trying something like this to even replace the number, but I don’t think the approach is quite right:
$stripped = preg_replace('/(MATERIALS)(,.*?){4}(,\d+?),/', '\2,', $stripped);
I tried going through a preg_match_all > for > if process, to at least get the conditional working, but I still have to replace the lines.
EDIT: I forgot the preg_match_all line that proceeded the loop.
preg_match_all('/MATERIALS.*/', $stripped, $materialsLines);
for($i=0;$i<sizeof($materialsLines[0]);$i++) {
$section = explode(",",$materialsLines[0][$i]);
if (strlen($section[5]) == 1) {
$section[5] .= ".001";
}
$materialsLines[0][$i] = implode(",",$section);
}
Why use a regex? You can simply explode the string on comma, check the value in [5], fix it and join the string back together.
http://codepad.org/g4r3pLpS
If reading multiple lines from a file:
if for some reason you HAVE to use a regex, this worked for me:
http://codepad.org/l7FfJlDe