Regular Expressions in Ruby and PHP
14 June 2007Here is a short comparison between Ruby and PHP. The task was to print the location of all HTML links in a webpage using regular expressions.
If anyone knows of a cleaner or more efficient way to do this in Ruby or PHP, please post it in the comments!
Ruby
require 'net/http'
#connect and get the webpage
host = Net::HTTP.new('www.site.com.au', 80)
body = host.get('/index.php', nil ).body
puts "Links found..."
#find link URIs
links = body.scan(/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/)
#print all link URIs
links.each {|id,uri| puts uri}PHP
<?php
$page = file_get_contents('http://www.site.com.au/index.php');
// find links
preg_match_all('/<a(.*?)href="(.*?)"(.*?)>(.*?)</a>/', $page, $links);
// links found
foreach($links[2] as $link)
{
print "$linkn";
}
?>

Gavin
Very cool article Rich! I'm really liking these posts about comparing ruby/php - great help for learning ruby... ;)