Page 1 of 1

preg_split / strtok don't quite do what I need

Posted: Thu Jan 22, 2009 12:00 am
by Luke
I'm trying to split a string with a regular expression (for my template engine), but keep what was in the regular expression in the result. For instance, let's assume we're parsing the string
the string wrote:{ i am between curly brackets } and im between nothing [ and im between square brackets ] and I am between nothing too
I want to split it with this regular expression "/([{}[]])/" and get this as the result:

Code: Select all

array(
    '{',
    ' i am between curly brackets ',
    '}',
    ' and im between nothing ',
    '[',
    ' and im between square brackets ',
    ']',
    ' and I am between nothing too'
)
preg_split doesn't provide a way to return the delimiters with the results :( any suggestions on how I might be able to accomplish this?

it's a bummer, this is the default behavior of python's re.split() method but I can't find a way to do it in php :(

Re: preg_split / strtok don't quite do what I need

Posted: Thu Jan 22, 2009 12:26 am
by requinix
The Ninja Space Goat wrote:preg_split doesn't provide a way to return the delimiters with the results
Sure about that? ;)

Code: Select all

preg_split($pattern, $subject, -1, PREG_SPLIT_DELIM_CAPTURE);
$0 isn't captured but every other subpattern is.

Re: preg_split / strtok don't quite do what I need

Posted: Thu Jan 22, 2009 12:28 am
by Christopher
PREG_SPLIT_DELIM_CAPTURE

Re: preg_split / strtok don't quite do what I need

Posted: Thu Jan 22, 2009 12:30 am
by Luke
Oh yay! :D

Re: preg_split / strtok don't quite do what I need

Posted: Thu Jan 22, 2009 12:33 am
by Luke
Oh now I see the problem I was passing flags in as the limit param :oops: