-1

我已经为此工作了一段时间,但我的正则表达式很弱。

我需要检查一个数字是否为整数(一位数),如果是,则在其上附加一个“.001”。问题是,它位于一行的中间,其中的值用逗号分隔。

材料,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

需要是

材料,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. 该行必须以“材料”开头。
  2. 有多个 MATERIALS 行。
  3. 该值将始终在 5 个逗号之后。

我正在尝试这样的事情来替换数字,但我认为这种方法不太正确:

$stripped = preg_replace('/(MATERIALS)(,.*?){4}(,\d+?),/', '\2,', $stripped);

我尝试通过 preg_match_all > for > if 进程,至少让条件工作,但我仍然需要替换这些行。

编辑:我忘记了preg_match_all进行循环的那一行。

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

3 回答 3

1

这很简单:

$str = preg_replace('/^(MATERIALS,(?:[^,]*,){4}\d+)(?=,)/m', "$1.001", $str);

请参阅此演示

于 2012-11-16T00:11:56.423 回答
0

这可以工作:(但idk你的字符串的整个结构)

$pattern = '#(MATERIALS,[0-9]{1},[0-9]{1},[0-9]{4};[^,]*,,[^,]),#';
$replacement = '${1}.001,'; // where ${1} references to pattern matches
$string = 'your string'
$matches  = preg_replace($pattern, $replacement, $string);
于 2012-11-15T23:22:00.953 回答
0

为什么使用正则表达式?您可以简单地用逗号分解字符串,检查 [5] 中的值,修复它并将字符串重新连接在一起。

$str = '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';
$line = explode(',',$str);
if(strpos($line[5],'.')===false){
    $line[5] .= '.001';
}
$str = implode(',', $line);

http://codepad.org/g4r3pLpS

如果从文件中读取多行:

$file = file("someFile.txt");
foreach($file as $key=>$line){
    $line = explode(',', $line);
    if($line[0] == 'MATERIALS'){
        if(strpos($line[5],'.')!==false){
            $line[5] .= '.001';
            $file[$key] = implode(',', $line);
        }
    }
}
file_put_contents("someFile2.txt", implode('',$file));

如果由于某种原因您必须使用正则表达式,这对我有用:

$str = '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
MATERIALS,1,1,9999;1 4PL1 PB_Mel,,1.101,6,0.173,0.173,0.375,0,0.375,0,0,0,0,2,0,1,1
FOO,1,1,9999;1 4PL1 PB_Mel,,1.1,6,0.173,0.173,0.375,0,0.375,0,0,0,0,2,0,1,1
BLAH,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
MATERIALS,1,1,9999;1 4PL1 PB_Mel,,567,6,0.173,0.173,0.375,0,0.375,0,0,0,0,2,0,1,1';

$str = preg_replace('/^(MATERIALS(,[^,]*){4},)(\d+),/m', '$1$3.001,', $str);
echo $str;

http://codepad.org/l7FfJlDe

于 2012-11-15T23:26:56.437 回答