Page 120 - Open Soource Technologies 304.indd
P. 120
Web Technologies-I
Notes
If you pass a string as the second argument to strrpos( ), only the first character is searched for.
To find the last occurrence of a multicharacter string, reverse the strings and use strpos( ):
$long = “Today is the day we go on holiday to Florida”;
$to_find = “day”;
$pos = strpos(strrev ($long), strrev($to_find));
if ($pos === false)
{
echo(“Not found”);
}
else
{
// $pos is offset into reversed strings
// Convert to offset into regular strings
$pos = strlen($long) $pos strlen($to_find);
echo(“Last occurrence starts at position $pos”);
}
Last occurrence starts at position 30
Searches Returning rest of String
The strstr( ) function finds the first occurrence of a small string in a larger string and returns from
that small string on. For instance:
$record = “Pradip, Kumar, 35, Riya”; $rest = strstr($record, “,”); // $rest is “,Kumar,35,Riya”
The variations on strstr( ) are:
stristr( )
Case-insensitive strstr( )
strchr( )
Alias for strstr( )
strrchr( )
Find last occurrence of a character in a string
As with strrpos( ), strrchr( ) searches backward in the string, but only for a character, not for an
entire string.
Searches using Masks
If you thought strrchr( ) was esoteric, you have not seen anything yet. The strspn( ) and strcspn
( ) functions tell you how many characters at the beginning of a string are comprised of certain
characters:
$length = strspn(string, charset);
114 LOVELY PROFESSIONAL UNIVERSITY