I love working with regular expressions. I had to use a preg function tonight that I haven’t called up in a long time. Using preg_replace, you can match for patterns in a string and then have them set to variables, and then modify them and do whatever you’d like with them. Read the actual documentation for a better explanation.
Anyway, here’s how I used it. I am working on parsing ChangeLogs, and on the page I display them, I want to replace any mention of ‘bug <bug number>’ with an actual href link to the bugzilla. Regular expressions makes it happen, baby!
A sample string, then, might be something like this: “Fixed everything. I rock. See bug #12345.”
Here’s my pattern: $pattern = ‘/(bug)( +\D)(\d+)/';
You need to know your regex syntax, but what this does is sets the word ‘bug’ to the first variable. The second variable is a space, repeated once or more, followed by one non-numeric character. The third variable is the bug #, or more accurately, any string that is only digits with a length of one or more characters. It just occured to me while writing this that I could have crammed the first and second together, but in the chance that I wanted to standardize or re-format the display, then I could play around with $2. In my case, though, I’m just going to leave it alone. Also, the second variable doesn’t need the space identifer if you don’t want, since \D would catch that, but you can do exactly what you want to make sure you get correct matches.
Using that pattern with preg_replace, PHP is going to assign the matching results to variables, numbered incrementally starting with 1. So, going back to my string, $1 would be ‘bug’, $2 would be ‘ #’, and $3 would be ‘12345’.
Now that I have my variables, I just create one more string to create my hyperlink. Here it is: $replacement = “<a href=’http://bugs.gentoo.org/show_bug.cgi?id=$3′>$1$2$3</a>”.
The actual code would be this: $str = preg_replace(‘/(bug)( +\D)(\d+)/’, “<a href=’http://bugs.gentoo.org/show_bug.cgi?id=$3′>$1$2$3</a>”, “Fixed everything. I rock. See bug #12345.”);
That would then return the original string with ‘bug #12345′ being a hyperlink.
Pretty cool stuff. I love working with regular expressions, and while this example is incredibly simple, there’s so much stuff you can do with it. Good times.