具有条件的特定数量的字符后的PHP Preg_replace

时间:2012-11-15 22:57:35

标签: php regex preg-replace

我一直在研究这个问题,但我的正则表达式很弱。

我需要检查一个数字是否是一个整数(单个数字),如果是,则附加一个“.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. 该行必须以“MATERIALS”开头。
  2. 有多个MATERIALS行。
  3. 该值始终位于5个逗号之后。
  4. 我尝试这样的东西甚至取代了这个数字,但我不认为这种方法是正确的:

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

    我尝试过preg_match_all>对于>如果进程,至少得到有条件的工作,但我仍然要更换线。

    编辑:我忘记了进行循环的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);
            }
    

3 个答案:

答案 0 :(得分:1)

这很简单:

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

请参阅 this demo

答案 1 :(得分: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);

答案 2 :(得分: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