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

StackOverflow https://stackoverflow.com/questions/14676441

  •  06-03-2022
  •  | 
  •  

Question

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

Was it helpful?

Solution

You may use strpos directly.

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

Hope this help :)

OTHER TIPS

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";
}

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";
}
?>

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

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

$str !== false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top