preg_split / strtok don't quite do what I need

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

preg_split / strtok don't quite do what I need

Post 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 :(
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

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

Post by Christopher »

PREG_SPLIT_DELIM_CAPTURE
(#10850)
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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

Post by Luke »

Oh yay! :D
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

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

Post by Luke »

Oh now I see the problem I was passing flags in as the limit param :oops:
Post Reply