Articles

Split string by delimiter in PHP

In PHP on September 29, 2011 by patrellery Tagged:


Here’s a quick tip to split a string using the pipe (|) delimiter in PHP. Let’s say you have a log or some sort of non usual string you want to split, such as:

$str = 'A|B\|B|C\\|D\\\|D';

You want this to look like:

$array[0] => 1
$array[1] => 2\|2
$array[2] => 3\\
$array[3] => 4\\\|4


Using the dark magic technique, you can accomplish this.

$array = preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $string);

Why? \\\\. matches a backslash followed by a character, (*SKIP)(*FAIL) skips it and \| matches your delimiter.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: