PHP strpos function: determining substring position

strpos() PHP - . , . .

PHP strpos() :

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



:

  • - $string, .
  • - $substring. mixed. , , . , .
  • , - $offset. $string, 0. , .

PHP strpos() , $substring $string. , .

, false.

, . , 0 - .

0 , false . (===), .





, strpos() - PHP-, .

Determining the position of a substring in a string




1. . , key monkeys.

<?php

$string = 'monkeys';
$substring = 'key';

$result = strpos($string, $substring);

//  $result - 3

?>


      
      



2. . KEY, PHP strpos() , . false.

<?php

$string = 'monkeys';
$substring = 'KEY';

$result = strpos($string, $substring);
echo($result === false);

?>
      
      



3. . , , .

<?php

$string = 'lifehack';
$substring = 'life';

$result = strpos($string, $substring);

if (!$result) {
  echo ' ';
}

if ($result == false) {
  echo ' ';
}

if ($result === false) {
  echo ' ';
}
?>
      
      



, , life lifehack.

4. $offset.

<?php

$string = 'love-and-love';
$substring = 'love';

$result1 = strpos($string, $substring);
$result2 = strpos($string, $substring, 3);

echo $result1; // 0
echo $result2; // 9
?>
      
      



, 3, "e".

PHP programming language




To determine the position of a substring in PHP, there are other functions that differ from strpos ():

  • stripos () - is not case sensitive;
  • strrpos () - defines the last occurrence;
  • strripos () - Searches for the last occurrence and is not case sensitive.




All Articles