-4

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.

Community
  • 1
  • 1
Loren Ramly
  • 1,091
  • 4
  • 13
  • 21

4 Answers4

3

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
leftclickben
  • 4,564
  • 23
  • 24
  • 2
    And why is the question down voted too? It is very basic level but people have to start somewhere, right? – leftclickben Feb 02 '13 at 10:26
  • Re: question getting downvoted, okay I get that. Re: my answer getting downvoted, and your comment on the question (which I don't have enough rep to reply to) "people got downvoted because they suggest overly complicated solutions instead of simply suggesting strpos" Well the question **stated** `preg_match`, so I believe that this is a starting point, not an ending point. Clearly there is something after the "start_to_date" token, which in likelihood will need to be further parsed. It seems like this person is studying regular expressions, so telling them to use `strpos` is invalid. – leftclickben Feb 02 '13 at 10:47
  • Anyway if it's a duplicate, why not just mark it as such? – leftclickben Feb 02 '13 at 10:49
  • Well the title stated both "regex" and "preg_match" so I'm not making any assumptions. – leftclickben Feb 02 '13 at 10:50
  • So you did, voted. (for the record at least lol) – leftclickben Feb 02 '13 at 10:51
3

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)

Nicholas Ruunu
  • 603
  • 5
  • 12
0

how about:

function cek_my_str($str){
    return preg_match('/^start_to_date/', $str)
}
Toto
  • 89,455
  • 62
  • 89
  • 125
0
function cek_my_str($str){
   $find = 'start_to_date';
   $substr = substr($str, 0, strlen($find));
   if($substr == $find){
    return true;
   }else{
    return false;
   }
}