Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

Regular expression challenge

なんだか世間では空前の正規表現ブームらしいですがw、ちょっと面白いネタを見つけました。


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.

以下のようなコード

<?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 . "}<br>";
}
?>

があり、出力が

{ 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” }

となるような

  • YOUR REG EXP HERE
  • YOUR REPLACEMENT STRING HERE

は何か?というものです。
すでに元エントリのコメントには色々書かれていますが、頭の体操にどうぞ。