Search code examples
phpstrposcontain

How to check if a string contains a dot followed by a number in PHP


I am trying to check if a string contains .2.

The following code works if I try to check if it contains a dot:

strpos($string, '.') !== false

But it doesn't work when use the following code:

strpos($string, '.2') !== false

nor

strpos($string, '\.2') !== false

Anyone an idea how to write it correctly? Thanks!


Solution

  • Ok, here is a working solution:

    $string = "this text contains the specified format: .233 and some nonsense.";
    preg_match('/^.*(\.\d+).*$/m', $string, $matches);
    
    var_dump($matches);
    
    //returns
    array(2) {
      [0]=>
      string(64) "this text contains the specified format: .233 and some nonsense."
      [1]=>
      string(4) ".233"
    }
    

    see the example at: http://regex101.com/r/eF0cU7/1