I’ll be the first to admit that I have trouble with regular expressions. But they’re incredibly useful when used in the right way. For instance, I was recently tasked with finding a way to insert a related podcast into a story node. To do this, I gave users the ability to add a shortcode into the text that would be parsed prior to viewing, so I could inject the necessary HTML.
Sounds simple. The shortcode would come in the form of [podcast id=”1234″]. Great. That’s easy to implement and simple enough to parse with PHP if I can find it in the text string.
preg_match('/[podcast id="d*"]/', $string, $podcastString);
This would work well, right? If you’ve done this type of thing before, you likely have your go-to source to test your regular expressions. I use www.regexr.com for my tests (they have a very clean and easy to use UI). So this will get all the instances of the podcast with the id if I use the /g flag in the regexr tool. But that flag won’t work with preg_match. That’s when I learned about preg_match_all. I know. I should know about this by now, but I’ve never dove into regular expression to any great length until now. So now this work just fine:
preg_match_all('/[podcast id="d*"]/', $string, $podcastString);
You can read about preg_match_all in the PHP docs.