how to check if '.'[dot] is present in string or not ? strstr is not working in php
Asked Answered
N

5

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

Navarre answered 3/2, 2013 at 19:39 Comment(2)
if($str === false) is better - as strpos returns an index if it is not false. if($str === false) echo 'No'; else echo 'OK';Ruvolo
strpos will never return an explicit boolean true value.Engineering
E
32

You may use strpos directly.

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

Hope this help :)

Epicarp answered 3/2, 2013 at 19:41 Comment(1)
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.Epicarp
V
0

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

$str !== false
Vestavestal answered 3/2, 2013 at 19:43 Comment(0)
O
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";
}
Oviparous answered 3/2, 2013 at 19:43 Comment(0)
R
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";
}
?>
Ramify answered 3/2, 2013 at 19:43 Comment(0)
B
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
Bondstone answered 3/2, 2013 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.