Tuesday 23 January 2018

Starts with

Tests if a text starts with an given string.

/**
 * StartsWith
 * Tests if a text starts with an given string.
 *
 * @param     string
 * @param     string
 * @return    bool
 */
function StartsWith($Haystack, $Needle){
    // Recommended version, using strpos
    return strpos($Haystack, $Needle) === 0;
}

// Another way, using substr
function StartsWithOld($Haystack, $Needle){
    return substr($Haystack, 0, strlen($Needle)) == $Needle;
}

$ExampleText = 'Hello world!';

if (StartsWith($ExampleText, 'Hello')){
    print 'The text starts with hello!';
}


$ExampleText = 'Evil monkey.';

if (!StartsWith($ExampleText, 'monkey')){
    print 'The text does not start with monkey!';
}

0 comments:

Post a Comment