preg_replace
-
We perform pattern based substitution in Ruby using
String#gsub, which is equivalent to PHP’spreg_replacefunction. A notable difference is that theString#gsubmethod is also used for string substitution in Ruby. We do this by simply providing a string instead of the regular expression pattern. This would be like using the str_replace function in PHP.In this example, we want to replace the domain in all emails with
foo.PHP
$string = 'joe@example.com; walter@example.org'; $result = preg_replace('/@([a-z0-9-]+)/', '@foo', $string); var_export($result); // => 'joe@foo.com; walter@foo.org'
Ruby
string = 'joe@example.com; walter@example.org' result = string.gsub(/@([a-z0-9-]+)/, '@foo') p result # => "joe@foo.com; walter@foo.org"
We can use backreferences in our
gsubreplacements just as we would withpreg_replaceby using\1,\2, etc in our replacement string.In this example, we prefix the existing domain with
mail.. Remember to escape backslashes used for the backreference.PHP
// Replace domain with mail.domain $string = 'joe@example.com; walter@example.org'; $result = preg_replace('/@([a-z0-9-]+)/', '@mail.\\1', $string); var_export($result); // => 'joe@mail.example.com; walter@mail.example.org'
Ruby
string = 'joe@example.com; walter@example.org' result = string.gsub(/@([a-z0-9-]+)/, '@mail.\\1') p result # => "joe@mail.example.com; walter@mail.example.org"
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.

