PHP Preg_replace after a specific amount of characters with a conditional

Posted by Marc Ripley on Stack Overflow See other posts from Stack Overflow or by Marc Ripley
Published on 2012-11-15T22:57:35Z Indexed on 2012/11/15 22:59 UTC
Read the original article Hit count: 249

Filed under:
|
|

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

  1. The line must start with "MATERIALS".
  2. There are more than one MATERIALS lines.
  3. 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.

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);
        }

© Stack Overflow or respective owner

Related posts about php

Related posts about regex