Show DevBest [PHP] Check if a string contains another string

Status
Not open for further replies.

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
I know the title seems a bit too much, but basically this function I've created checks if a string contains another string, for example:

Code:
Does "Mark Eriksson" contain "Mark"
Answer = Yes/True/1

It also checks if a string contains another string on a case sensitive basis:

Code:
Does "Mark Eriksson" contain "mark" on a case sensitive basis
Answer = No/False/0

Seems confusing? Right, well hopefully looking at the code might enlighten you.

PHP:
<?php
function Contains( $str1, $str2, $case_sensitive=true )
{
/**
 * A simple function to check if a string contains another string.
 * $str1 - string - The string to find.
 * $str2 - string - The string to search within.
 * $case_sensitive - bool - Is $str1 case sensitive?
 */

/**
 * Examples:
 * Contains( "Mark", "Mark Eriksson", false )      returns true
 * Contains( "Mark", "Marc Eriksson" )             returns false
 * Contains( "mark", "Mark Eriksson", false )      returns true
 */
$i = ( $case_sensitive == true ) ? "" : "i";
return ( preg_match( "/" . $str1 . "/" . $i, $str2 ) );
}

echo Contains( "Mark", "Mark Eriksson", true )  ? "True" : "False";
echo "<br />";
echo Contains( "Mark", "Marc Eriksson" )        ? "True" : "False";
echo "<br />";
echo Contains( "mark", "Mark Eriksson", false ) ? "True" : "False";
?>

Enjoy,
- m0nsta.
 

Tr0ll.

Member
Nov 20, 2010
99
5
PHP:
/*
    * Figures out if a string contains another string
    * @return the result.
    */
    final public function Contains($haystack, $needle){
        return strpos($haystack, $needle);
    }

..?
 

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
PHP:
/*
    * Figures out if a string contains another string
    * @return the result.
    */
    final public function Contains($haystack, $needle){
        return strpos($haystack, $needle);
    }

..?
Yeah of course that will work, but making the case-sensitive part would be an arse as you have to completely rename 'strpos' to 'stripos' so you will need a switch/if statement in your Contains() function.
 
Status
Not open for further replies.

Users who are viewing this thread

Top