This post covers the Searching section of the Strings chapter when studying for the Zend PHP 7 Certification.
Some of the string functions for searching characters in a given string can be seen below.
The strpos()
function finds the position, starting from zero, of the first occurrence of a substring in a string. The function can take up to three parameters.
$newstring = 'abcadef abcdef';
echo $pos = strpos($newstring, 'a'); // Outputs: 0
echo $pos = strpos($newstring, 'a', 1); // Outputs: 7
$newstring = 'abcadef abcdef';
echo $pos = strpos($newstring, 'a', 1); // Outputs: 4
As of PHP version 7.1, negative offsets have been introduced. If the value is negative, search will instead start from that many characters from the end of the string, searching backwards.
Similar to strpos()
, there is stripos()
which is a case-insensitive version of the function.
$newstring = 'abcdef';
$pos = strpos($newstring, 'A');
$pos2 = stripos($newstring, 'A');
var_dump($pos);
var_dump($pos2);
// Outputs:
boolean false
int 0
The strlen()
function returns the length of a given string. It takes one parameter, which is the string being measured for length.
$str = 'abcdef';
echo strlen($str); // 6
$str = ' ab cd ';
echo strlen($str); // 7
Note that using strlen()
on an array will return NULL
and generate a warning.
The strstr()
function finds the first occurrence of a string. The function takes three parameters.
true
, strstr()
returns the part of the haystack before the first occurrence of the needle (excluding the needle)$email = 'name@example.com';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
View the other sections:
Note: This article is based on PHP version 7.1.