You may not know this, but the latest version of PHP comes with avery powerful set of string manipulatation tools. This article takes anin-depth look at these tools and illustrates how they can save you time andeffort in your daily development activities.
You can use the case-sensitive strpos() function to locate the first occurrence of a character in a string,
<?
$str = "Robin Hood and his band of merry men";
// returns 0
echo strpos($str, "R");
?>
and the strrpos() function to locate its last occurrence.
<?
$str = "Robin Hood and his band of merry men";
// returns 33
echo strrpos($str, "m");
?>
The substr_count() function comes in handy if you need to
know how many times a specific patter recurs in a string.
<?
$str = "'tis said that the is the most common word in the English language,
and e is the most common letter";
// returns 4
echo substr_count($str, "the");
?>
The strstr() function scans a string for a particular pattern
and returns the contents of that string from the point onwards (for a case-insensitive version, try stristr()).
<?
$str = "As Mulder keeps saying, the truth is out there";
// returns "the truth is out there"
echo strstr($str, "the");
?>
If you need to compare two strings, the strcmp() function
performs a case-sensitive binary comparison of two strings, returning a negative value if the first is "less" than the second, a positive value if it's the other ways around, and zero if both strings are "equal". Take a look at a couple of examples to see what this means:
<?
// returns -1 because a < s
echo strcmp("apple", "strawberry");
// returns 1 because u > p (s == s)
echo strcmp("superman", "spiderman");
// returns 0
echo strcmp("ape", "ape");
?>
You can perform a case-insensitive comparison with the
strcasecmp() function, or adopt a different approach with the very cool "natural order" comparison, which compares strings the way humans (rather than computers) would.