combining two regexes

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post by GeertDD »

Wait, I'm not giving up already :wink:

Code: Select all

$regex = '/[^\[\]\s]++|(?=\[\])/';
$str   = 'foobar2f[f1][f][]';

preg_match_all($regex, $str, $matches);

print_r($matches[0]);
Output:

Code: Select all

Array
(
    [0] => foobar2f
    [1] => f1
    [2] => f
    [3] => 
)
This basically is my original regex pattern alternated with a check for empty square brackets. Locating an empty pair of them will fill the $matches array with an empty string. Will this do the trick for you?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I'm in your dept :D
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

GeertDD wrote:
stereofrog wrote:

Code: Select all

$re = '~\w+(?=\[)|(?<=\[)\w+(?=\])~';
Is this what you're looking for?
If it is, I think you're needlessly complicating that regex.

Try this pattern:

Code: Select all

/[^\[\]]+/

Given a string like this "foo[bar] XYZ qux[quux]", should the expression also match "XYZ"? I was under the impression that Jcart only needs the words between "[ ]" or immediately before "[". Your expression apparently won't work for this case.
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Post by GeertDD »

stereofrog wrote:Given a string like this "foo[bar] XYZ qux[quux]", should the expression also match "XYZ"? I was under the impression that Jcart only needs the words between "[ ]" or immediately before "[". Your expression apparently won't work for this case.
Jcart isn't clear about that. This would work if you don't want to match 'XYZ':

Code: Select all

/[^\[\]\s]++(?=\[)|(?=\[\])/
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Sorry for not being clear about it.. XYZ is most certainly valid. Basically what I'm doing this on is a <input> attribute name to map it's name to it's value (possibly an multimensional array which is why we are doing this ;))

Thanks.
Post Reply