Search code examples
phpstrpos

simple strpos() not working with "[" char, why?


why does if i do:

if(strpos("[","[rgeger]")){ 
echo 'hey'; 
}

it doesn't prints anything?

try this with a string:

function return_tags($keywords){
 if($keywords){
  $k_array = array();

  foreach($this->check($keywords) as $key=>$value){

    array_push($k_array, $value);
  }

  $last_array = array();
  foreach($k_array as $key=>$value){
    if(strpos("[", $value) && strpos("]", $value) && strlen($value) >= 2){
      $value = '<span class="tag">'.$value.'</span>';

    }
    array_push($last_array, trim($value));

  }
  return $last_array;

 }else{
  return false;
 }
}

string example

  $keywords = "freignferi eiejrngirj erjgnrit [llll] [print me as tag]";

did you see any <span> element printed in html?


Solution

  • It looks like you swapped the arguments:

    int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
    

    So if you want to know if a [ is in your string [rgeger]:

    if (strpos("[rgeger]", "[") !== false) { 
      echo 'hey'; 
    }
    

    (Source: http://php.net/strpos)