在主题中使用逗号进行反向引用preg_replace

时间:2015-09-02 19:33:58

标签: php regex preg-replace

你能帮我找到preg_replace语法,这样我可以复制丢失的价格吗? 主题是:

...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat

我的输出想要:

...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat

我试过

preg_replace("(\W+),,nomaterwhat$", "$1,$1,nomaterwhat", $string);

3 个答案:

答案 0 :(得分:2)

如果你使用str_getcsv,你可以这样做:

$data = "CSV VALUES";

$lines = explode("\n", $data);
foreach ($lines as $line) {
    $temp = str_getcsv($line);
    echo '<pre>' . print_r($temp, true) . '</pre>';
}

然后你可以把它们放到一个像这样的数组中:

$data = "CSV VALUES";
$lines = explode("\n", $data);
$output = array();
foreach ($lines as $line) {
    $temp = str_getcsv($line);
    $temp[5] = ($temp[5] == '') ? $temp[4] : $temp[5];
    $output[] = $temp;
}
echo '<pre>' . print_r($output, true) . '</pre>';

$temp[5]替换为第二个价格的位置。

答案 1 :(得分:2)

忽略更复杂的情况应该这样做:

FindNextFile

答案 2 :(得分:1)

你的正则表达式有一些问题。
 1.没有分隔符
 2.没有m修饰符,因此$是字符串的结尾,而不是行。
 3. \W+是非a-z0-9和/或_所以你不会得到     无论如何都有金钱价值。

试试这个:

$string = '...nomaterwhat13124123,"321,00",,nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00",,nomaterwhat
...nomaterwhat31313,"241,00",,nomaterwhat';
echo preg_replace("/,(\"\d+,\d{2}\"),,nomaterwhat$/m", ",$1,$1,nomaterwhat", $string);

输出:

...nomaterwhat13124123,"321,00","321,00",nomaterwhat
...nomaterwhat12321,"322,20","134,00",nomaterwhat
...nomaterwhat1321,"211,00","211,00",nomaterwhat
...nomaterwhat31313,"241,00","241,00",nomaterwhat

正则表达式演示:https://regex101.com/r/hE2zQ7/1

PHP演示:http://ideone.com/OanPN1