Regular Expressions in Ruby and PHP

June 14, 2007

Ruby

Here 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";
}

?>

Leave a Comment

Previous post:

Next post: