I’m trying to grab the content from some Craigslist tags in PHP/Codeigniter. The tags I need to parse look like:
<!-- CLTAG xstreet0=Inman -->
<!-- CLTAG xstreet1=Moscrop -->
<!-- CLTAG city=Burnaby -->
<!-- CLTAG region=BC -->
For each one of these tags, which are contained in a $content variable, I’d like to grab each name/value pair. Tragically, I am the SUCK with regular expressions, but so far this at least finds the opening string of one of the tags:
$pattern = '/<!-- CLTAG city=/';
preg_match($pattern, $content, $matches);
echo "<pre>";
print_r($matches);
echo "</pre>";
Where I’m stuck is now to pull a pair of name/value out, so that I have ‘city’ and ‘burnaby’ to work with. Ditto for each of the others. I suspect a substr or something here?
You can make your life a bit easier by including the “PREG_SET_ORDER” constant and
preg_match_all()instead ofpreg_match()like so:If you encountered a scenario where no “xstreet1” value was specified (because addresses can work that way), you would need to slightly modify the regex pattern and add a check to ensure the second group exists in your loop:
Note how there’s a ‘?’ added after the second capture group in the regular expression. This tells the regex compiler that this group may or may not occur.