strstr

  • We can find the first occurrence of a string in Ruby by using the String#match method. This will return a MatchData object which we can inspect to retrieve more information about the matched characters.

    PHP

    print strstr("name@example.com", "@");
    // => @example.com

    Ruby

    match = "name@example.com".match('@')
    puts match[0] + match.post_match
    # => @example.com

    The strstr function is often used to simply check for the presence of a substring within a string. This is usage is accomplished in Ruby by using the String#include? method.

    PHP

    $result = (strstr("name@example.com", "@") !== false);
    var_export($result);
    // => true

    Ruby

    puts "name@example.com".include?("@")
    # => true

    see also

strrpos strtok

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.