PHP strpos function

 The PHP strpos function is used to find the numeric position of the key character in the original string. For example, using the strpos function to query the numeric position of the letter e in Hello, it will return a result like 1, and the first letter starts from 0 Calculation. The strpos function will automatically determine the case of key characters in English letters, that is to say, A and a are different characters under the identification of the strpos function. If you want to make the effect of "insensitive to the case of English letters", Please use the stripos function to determine the key character.


Basic syntax of PHP strpos function

int strpos( string $haystack, string $needle, int $offset)


The first parameter $haystack of the strpos function represents the original string, which is the string to be inspected. It is a required item. The second parameter $needle is the key character. The strpos function will go according to $needle. Query whether $haystack contains a compatible string of related constructions. If there is, it will return to the position of the number (starting character is counted from 0). If there is no matching character, it will return false or its equivalent value. The non-Boolean value of. The third parameter $offset is an optional item, used to specify the position from which to start the calculation, also called the offset. The returned result position is relative to the starting position of $haystack. Please refer to Example 2.

PHP strpos function example 1
<?php
$NewString='Welcome to wibibi.Have a good day.';
$FindKey='w';
$TryStrpos=strpos('Welcome to wibibi.Have a good day.','w');

if($ TryStrpos === false){ echo'no
  find';
}else{
  echo'The key character w is at the first position of the original string'.$TryStrpos.';
}
?>
The output of the above example
The key character w exists in the original string, and it is in the 11th position
In the if...else conditional judgment, we use the wording ($TryStrpos === false), the main purpose is to avoid incorrect judgments caused by non-Boolean values. Since the strpos function automatically distinguishes between uppercase and lowercase letters, the output can find that the lowercase w letter is in the 11th position instead of the 0th position.

PHP strpos function example 2: using offset
<?php
echo strpos('Welcome to Wibibi.Have a good day.','W').'<br>';
echo strpos('Welcome to Wibibi.Have a good day.','W',2) ;
?>
The output of the above example
0
11
The result of the first output did not use the offset parameter. The strpos function judged that the position of the first uppercase English letter W was at 0. In the second output, the strpos function added the offset parameter, so it was automatically Skip the first English letter W, find the second W, relative to the starting position of the original string, the second W is at the 11th position.

Post a Comment

0 Comments