George Reith George Reith - 5 months ago 29
PHP Question

PHP: explode but ignore escaped delimiter

I have a flatfile database and it is data seperated by delimiters.

I allow people to use the delimiter in their input but I make sure to escape it with a

\
beforehand.

The problem is my
explode()
function still attempts to split the escaped delimiters, so how do I tell it to ignore them?

Answer

Use preg_split instead. By using a regex you can match a delimeter only if it is not preceded with a backslash.

Edit:

preg_split('~(?<!\\\)' . preg_quote($delimeter, '~') . '~', $text);