str_replace

  • All replacements in Ruby are done using String#gsub. This method does both regular expression and string based replacements.

    PHP

    $result = str_replace('Hello', 'Hi', 'Hello world');
    var_export($result);
    // => 'Hi world'

    Ruby

    p "Hello world".gsub("Hello", "Hi")
    # => "Hi world"

    Ruby also has the String#gsub! method which modifies the string value directly.

    Ruby

    my_string = "Hello world"
     
    # the original string remains the same (we use the return value)
    my_string.gsub("Hello", "Hi")
    p my_string
    # => "Hello world"
     
    # the original string is modified
    my_string.gsub!("Hello", "Hi")
    p my_string
    # => "Hi world"

    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.