In many
cases, these alternative functions actually perform much faster than their regular expression counterparts.
Other String-Specific Functions
In addition to the regular expression??“based functions discussed in the first half of this
chapter, PHP offers more than 100 functions collectively capable of manipulating
practically every imaginable aspect of a string. To introduce each function would be
out of the scope of this book and would only repeat much of the information in the
PHP documentation. This section is devoted to a categorical FAQ of sorts, focusing
upon the string-related issues that seem to most frequently appear within community
forums. The section is divided into the following topics:
??? Determining string length
??? Comparing two strings
??? Manipulating string case
??? Converting strings to and from HTML
??? Alternatives for regular expression functions
CHAPTER 9 ?– S TRINGS AND REGULAR EXPRESS IONS 249
??? Padding and stripping a string
??? Counting characters and words
Determining the Length of a String
Determining string length is a repeated action within countless applications. The
PHP function strlen() accomplishes this task quite nicely. This function returns the
length of a string, where each character in the string is equivalent to one unit. Its
prototype follows:
int strlen(string str)
The following example verifies whether a user password is of acceptable length:
$pswd = "secretpswd";
if (strlen($pswd) < 10)
echo "Password is too short!";
else
echo "Password is valid!";
?>
In this case, the error message will not appear because the chosen password
consists of ten characters, whereas the conditional expression validates whether the
target string consists of less than ten characters.
Pages:
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327