0

Ok regex experts. I'm having a ton of trouble trying to make a regex pattern for my needs. The goal: Take a search query such as "good food type:post format:gallery" and parse the type or format or both from the string. This is what I wrote, but doesnt work unless both type and format are present and type comes before format. Ideally, either type or format could be present.

$query = "Great food type:post format:gallery";
preg_match('/(.*?(?<=\btype:)(?P<type>[a-z]*\w+))(.*?(?<=\bformat:)(?P<format>[a-z]*\w+))/', $query, $matches);

I image I need the returned $matches to be named as well right? Thanks,

1
  • Why making life harder? Can't you just explode on spaces and iterate to check for entries beginning with type: or format: ? Jan 11, 2012 at 22:32

1 Answer 1

3

I don't think you'll want to use a regex for this. It'll be a pain to maintain and update when you add more operators like type: and format: Also the regex then depends on ordering of what's entered.

A simple approach might be like

$tokens=explode(" ",$searchString);
foreach($tokens as $token){
     if(preg_match('~([^:]+:(.*)~',$token,$flagMatch)){
         $flags[$flagMatch[1]]=$flagMatch[2];
     }
     $searchtokens[]=$token
}

Obvious caveat with that example is exploding straight on space so you wouldn't be able to handle "quoted terms" that should be treated as one.

2
  • Thanks a bunch... explode is a method I probably underuse. I tweaked the regex and loop to fit my needs and ended up with this: code foreach($tokens as $token){ if(preg_match('~([a-z]+[^:])+:([a-z0-9]+)~',$token,$flagMatch)){ $flags[$flagMatch[1]] = $flagMatch[2]; }else{ $searchtokens[] = $token; } } code This way, the search operator becomes the whole word in the first match and the second match must be one or more characters, but not spaces,etc... The else statement separates the normal keywords from the find types. Jan 12, 2012 at 16:23
  • My bad on the formatting. I tried to re-edit it, but my 5 minutes was up :( Jan 12, 2012 at 16:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.