繁体   English   中英

PHP正则表达式替换计算

[英]PHP regular expression replacing calculations

这是来自大型文本文件的一些示例文本。

(2, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(3, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(4, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(5, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(6, 1, 3, 2, 'text...','other text...', 'more text...', ... ), 

现在,我需要在第一列的每个值上添加19。

(21, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(22, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(23, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(24, 1, 3, 2, 'text...','other text...', 'more text...', ... ),
(25, 1, 3, 2, 'text...','other text...', 'more text...', ... ), 

preg_replace_callback()似乎是解决方案,但我并不真正习惯于正则表达式...

preg_replace_callback(
    '/(?<=\()(\d+)(?=,.+\),?\v)/',
    function($match) {
        return (string)($match[1]+19);
    },
    $large_text
);

这将为stdin做到。

// Your function
function add19($line) {
    $line = preg_replace_callback(
        '/^\(([^,]*),/',
        create_function(
            // single quotes are essential here,
            // or alternative escape all $ as \$
            '$matches',
            'return ("(" . (intval($matches[1])+19) . ",");'
        ),
        $line
    );
    return $line;
}

// Example reading from stdin
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
    $line = add19(fgets($fp));
    echo $line;
}
fclose($fp);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM