12

I am trying to see if . [dot] is present in string or not.

I have tried strstr but it returns false.

here is my code :-

<?php
$str = strpos("true.story.bro", '.');
if($str === true)
{
        echo "OK";
} else {
        echo "No";
}
?>

I want to see if '.' is present in string or not, I can do with explode, but i want to do in 1 line, how could i do that ?

Thanks

UserHex
  • 143
  • 1
  • 1
  • 10
  • `if($str === false)` is better - as `strpos` returns an index if it is not *false*. `if($str === false) echo 'No'; else echo 'OK';` – Déjà vu Feb 03 '13 at 19:42
  • `strpos` will never return an explicit boolean `true` value. – nickb Feb 03 '13 at 19:51

5 Answers5

31

You may use strpos directly.

if (strpos($mystring, ".") !== false) {
    //...
}

Hope this help :)

Frederik.L
  • 5,522
  • 2
  • 29
  • 41
  • You're welcome! In fact, `strpos` is a "confused?" int that return false if the needle part is not present in the sentence. Just pay attention to the operator `!==` that validate the type of strpos, as `!=` could also make this true if strpos return an int that can be equivalent to FALSE, which would be an error. – Frederik.L Feb 03 '13 at 20:11
0

Strpos returns the index of the first occurrence of the second argument in the first one. Use

$str !== false
Zombo
  • 1
  • 62
  • 391
  • 407
0

Your using strpos incorrectly. It returns an integer of the first occurrence of the string and not true if it was found.

Try this code instead:

$str = strpos("true.story.bro", '.');
if($str !== false)
{
    echo "OK";
} else {
    echo "No";
}
SameOldNick
  • 2,397
  • 24
  • 33
0

If "." is at the first byte in the string, strpos will correctly return zero. That inconveniently evaluates equal to false. Invert your logic like so:

<?php
$str = strpos("true.story.bro", '.');
if($str === false)
{
        echo "No";
} else {
        echo "OK";
}
?>
Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65
0

return of strpos is either integer(0 to strlen(string)-1) or boolean (false), then, you can check this using two cases:

$pos = strpos('this is text with . dot', '.');
if(is_int($pos)){
 echo 'dot is found';
}else{
 echo 'dot not found';
}

or 
if($pos === false){
 echo 'dot not found';
}else{
 echo 'dot found';
}

note strpos('. test', '.') = 0  then is_int(0) ?  true