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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With