正则表达式,PHP preg_match使函数如何在字符串以str_to_date开头时返回true [duplicate]

Possible Duplicate:
PHP: How to check if a string starts with a specified string?

I am struggling to create a function to check this string starting from start_to_date or not, below is my implement.

$string = 'start_to_date-blablablabla';
if(cek_my_str($string)){
   echo "String is OK";
}

// tes again
$string2 = 'helloworld-blablablabla';
if(cek_my_str($string2)){
   echo "String not OK";
}

function cek_my_str($str){
   // how code to return true if $str is string which start with start_to_date
}

Thanx.

how about:

function cek_my_str($str){
    return preg_match('/^start_to_date/', $str)
}

To do it with Regex, you would do:

return preg_match('/^start_to_date/', $str);

Key reference: http://www.regular-expressions.info/

However, the PHP Manual for preg_match states

Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster.


By the way, you should look into unit testing: http://www.phpunit.de/manual/current/en/

This is a way of encapsulating exactly what you are doing in reusable tests.

function cek_my_str($str){
   $find = 'start_to_date';
   $substr = substr($str, 0, strlen($find));
   if($substr == $find){
    return true;
   }else{
    return false;
   }
}

In this case the best thing to do is:

if(strpos($string, 'start_to_date') === 0) { ... }

strpos() checks if 'start_to_date' is on position 0 (beginning)