PHP String
Finding length of a PHP string using strlen
$str = 'test string';
$len = strlen('$str');
echo $len; // this will output 11
Checking substring existence using strpos
$str = 'test string'; $sub_str = 'str'; if (strpos($str, $sub_str) === false) echo "Substring not found"; else echo "Substring exist in given string";Note the use of === operator because == will not work as expected since the return position can be 0 (start of string).
The offset value can be used here to specify from where to start searching. see example below:
$str = 'abcdefabcdef'; echo strpos($str, 'a', 1); // will print 6 not 0
Finding occurrence of a string
$email = 'user@domain.com'; $domain = strstr($email, '@'); echo $domain; // this will print '@domain.com'So strstr will return part of the string, starting from the given substring. If given substring does not exist, it will return FALSE. This string function is case-sensitive. For case-insensitive searches stristr is used , see below:
$domain = stristr('USER@EXAMPLE.com', 'e');
echo $domain; // This will print ER@EXAMPLE.com
Function strrchr(string str, char chr) is used to find the last occurrence of a character.
This function returns the portion of string which starts at the last occurrence of given character and goes up to the end. see example below:
echo strrchr("abcdexyz", "e"); // will print exyz
echo substr(strrchr("module.filename.html", "."),1); // will print html
Return part of a string: Substring
echo substr("abcdef", 1); // will output "bcdef" , start 1 to end.
echo substr("abcdef", 1, 3); // will output "bcd", 1 to 3
echo substr("abcdef", 0, 4); // will output "abcd"
echo substr("abcdef", 0, 8); // will output "abcdef"
Using curly braces we can also return a character at given position. For example
$string = 'abcdef';
echo $string{0}; // will print a
echo $string{3}; // will print d
We can also use negative value of start parameter to return part from the end of string. see examples below:
substr("abcdef", -1); // returns "f"
substr("abcdef", -2); // returns "ef"
substr("abcdef", -3, 1); // returns "d"
Also negative value of length parameter can be used. In this case it will omit that many characters from the end of the string. See below:
echo substr("abcdef", 0, -1); // will omit 1 char from the end and returns "abcde"
echo substr("abcdef", 2, -1); // returns "cde"
echo substr("abcdef", 4, -4); // returns ""
echo substr("abcdef", -3, -1); // returns "de"