REGEX以两个元字符开头

时间:2018-12-07 08:58:24

标签: php regex csv

我的REGEX有一个问题。我想搜索以“”开头且必须包含一个或多个换行符的字符串段。

$csv = xxxx,xxxx,"segment with

line break",xxxx,"segment with no line break",xxxx;

这是我的REGEX:

$file = fopen('google.csv', 'r');

$csv = file_get_contents('google.csv');


function matches($matches)
{
    return preg_replace("#\n|\r|\t#", "£", $matches);

}

preg_replace_callback('/,"(?=[^"]*\R)[^"]*"/', 'matches', $csv);

当我删除第一个元字符'时,它可以工作,但其余字符串存在一些问题。而且当我添加逗号时,我的REGEX不起作用。

可以帮我吗?

1 个答案:

答案 0 :(得分:0)

preg_replace的第三个参数必须为字符串:

preg_replace("#\n|\r|\t#", "£", $matches[0]);
//                                      ^^^

整个代码:

$csv = 'xxxx,xxxx,"segment with

line break",xxxx,"segment with no line break",xxxx';

function matches($matches) {
    return preg_replace("#\n|\r|\t#", "£", $matches[0]);
}

$res = preg_replace_callback('/,"(?=[^"]*\R)[^"]*"/', 'matches', $csv);
echo $res;

输出:

xxxx,xxxx,"segment with££line break",xxxx,"segment with no line break",xxxx