Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem capturing delimiter with preg_split

Tags:

php

preg-split

I have a pipe-delimited dump file from an SQL Server, and I want to import it into MySQL. The lines are delimited by \r\n, and that sequence also occurs in some fields! So I want to use a regular expression to find the actual lines and make an INSERT statement out of them.

However, I'm having trouble including the delimiter in my match string. I thought using PREG_SPLIT_DELIM_CAPTURE would do the trick but apparently I'm doing something wrong. My delimiter is three spaces followed by three numbers, which is actually the id that I need for the row:

$ cat test.php
<?
$string = '   897|a|Hello\r\n   583|b|Line\r\nBreak\r\n   332|c|Yet\r\nMore\r\nLine\r\nBreaks\r\n';

$lines = preg_split( '/   \d{3}\|/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);
print_r($lines);

$ php test.php
Array
(
    [0] => 
    [1] => a|Hello\r\n
    [2] => b|Line\r\nBreak\r\n
    [3] => c|Yet\r\nMore\r\nLine\r\nBreaks\r\n
)

My delimiters are missing.

$ php -v
PHP 5.3.3-7+squeeze1 with Suhosin-Patch (cli) (built: Mar 18 2011 17:22:52) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

What am I doing wrong, or how do I get what I want?

like image 483
user151841 Avatar asked Jan 17 '26 20:01

user151841


1 Answers

You need to group your delimiter into parenthesis, or else the _DELIM_CAPTURE will have no effect.

$lines = preg_split( '/   (\d{3}\|)/', $string, NULL, PREG_SPLIT_DELIM_CAPTURE);

Here, the manual mentions it en passant as flag description:

PREG_SPLIT_DELIM_CAPTURE
If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.

like image 86
mario Avatar answered Jan 20 '26 10:01

mario