如何使用PHP检查给定格式的字符串?

I have many headlines in my project like:

00.00.2014 - Headline Description e.t.c.

I want to check with php if the given strings contain the format 00.00.0000 - in front. The part after the - doesn't matter.

Can someone help me with something like:

$format = '00.00.0000 -';

if ($string MATCHES $format IN FRONT) {
    // ...some code...
}

This should work:

if (preg_match("/^\d{2}\.\d{2}\.\d{4}\s\-\s.*$/", $string) === 1) {
    // $string matches!
}

Explanation:

  • ^ is "the beginning of the string"
  • \d is any digit (0, 1, 2, ..., 9)
  • {n} means "repeated n times"
  • \. is a dot
  • \s is a space
  • \- is a minus sign
  • . is "any single character"
  • * means "repeated 0 or more times`
  • $ means "end of the string"

Use the strpos function. Something like this:

if (strpos($string,'00.00.0000 -') !== true) {
//some code
}

I don't have a dev environment to test this out on but i'll give you some psuedocode:

I'm unsure of the context, but you can test this function on any given STRING:

Function:

 Boolean hasCorrectFormat($myString){

         //Here take the string and cut it into a char array.

         $charArray = str_split($myString); 

         //This will give you a char array. Compare the first 12 elements of this
         //array to see if they are correct. If its supposed to be number make
         //sure it is, if its supposed to be a "." make sure it is..etc
         //"00.00.0000 -" is 12 characters. 

         if(!isNumeric(charArray[0])){
             return false;
          }
          else if(!isNumeric(charArray[1])){
               return false;
          }
          else if(charArray[2] != "."){
               return false;
          }
        //so on and so forth.....
           else {return true}
    }

Like i said i can't test this, and i can almost guarantee you this code wont run. This should give you the logic involved though.

Edit: also i wrote this assuming you dont literally mean "00.00.0000" but rather "xx.xx.xxxx" x being any number 0-9. If you need to make sure it is literally zeros then just cut your string to be the first ten chars and compare it.