Regular expression challenge
Published: Thu, 18 Oct 2007 17:40:26 GMT
Updated: Sat, 22 Mar 2025 15:38:06 GMT
After the success of my "a bit of fun" challenge, a few people asked for some more challenges. So I was answering a question on a mailing list that I'm a member of and I thought it would be a good topic for a little challenge and help sharpen everyone's regular expression skills.
The rules
Only one valid regular expression is allowed and no other code can be used other than the regular expression itself.
The input
<pre lang="php"> <?php $strings = array('from sutton-in-craven to anywhere', 'from leeds, west yorkshire to harrogate, north yorkshire', 'to leeds via guisley from harrogate','from harrogate to leeds', 'via guisley from harrogate to leeds','from harrogate to leeds'); foreach($strings as $string) { $output = preg_replace("/YOUR REG EXP HERE/i", 'YOUR REPLACEMENT STRING HERE', $string); echo "{" . $output . "} "; } ?> </pre>The output
This is what the output should look like:- { from: "sutton-in-craven" to: "anywhere" } { from: "leeds, west yorkshire" to: "harrogate, north yorkshire" } { to: "leeds" via: "guisley" from: "harrogate" } { from: "harrogate" to: "leeds" } { via: "guisley" from: "harrogate" to: "leeds" } { from: "harrogate" to: "leeds" }
Enjoy and good luck :)
The winner
Well I thought how can I judge the winner? It can't really be the first one because of timezones so I thought the neatest and smallest regular expression. At the moment there is no prize but if there are any companies out there willing to purchase a book for the winner and for future contests let me know and I shall place your logo and link on this and future contests.
At first I thought the winner was Jason but I double checked his regular expression and it didn't seem to give the correct output. So the winner is.... Adnan Ali with /(to|from|via) (.*?)(?= (?1) |$)/i
Well done Adnan!!! Adnan has a blog which is available here:- http://www.adnanali.net/