preg_match
-
We match a pattern in Ruby strings using the
matchmethod. Ruby’smatchmethod works differently thanpreg_matchin how it returns matches. We usually want to know two different things when we match data: If the pattern matched, and what specific strings sections were matched.PHP returns an integer to tell us if the data matched (either
0or1) and populates a matches array by reference. Ruby returns aMatchDataobject when the pattern matches, andnilwhen something doesn’t. We can inspect theMatchDataobject to find the actual string matches.In this example, we try to match the different components of a list of email addresses. Both
preg_matchandString#matchonly match the first occurrence of the pattern.PHP
$string = 'joe@example.com; walter@example.org'; $result = preg_match('/([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i', $string, $matches); var_export($result); // => 1 var_export($matches); // => array('joe@example.com', 'joe', 'example', 'com')
Ruby
string = 'joe@example.com; walter@example.org' matches = string.match(/([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i) p !matches.nil? # => true p matches # => #<MatchData:0x1ed138> p matches[1] # => "joe" p matches.to_a # ["joe@example.com", "joe", "example", "com"]
see also
Looking for Rails or PHP web application development, integration, and training?
Rails for PHP is brought to you by Maintainable Software. Get custom web applications and personalized training from the authors of the book and website.

