141Chapter 8StringsIn this section, we present the basic (Web design course)
141Chapter 8StringsIn this section, we present the basic functions for inspecting, comparing, modifying, andprinting strings. If you want to be really comfortable with string manipulation in PHP, youshould probably have at least a passing acquaintance with everything in this section. Boththe regular expression functions and the more abstruse string functions can be found inChapter 22. A note for C programmers: Many of the PHP string function names should be familiar to you. Just keep in mind that, because PHP takes care of memory management for you, the func- tions that return strings are allocating the string storage on their own and do not need to begiven a preallocated string to write into. Inspecting stringsWhat kinds of questions can you ask strings? First on the list is how long the string is, usingthe strlen()function (the name is short for string length). $short_string = This string has 29 characters ; print( It does have . strlen($short_string) . characters ); This code gives the following output: It does have 29 charactersKnowing the string s length is particularly useful in form validation or for situations in whichwe d like to loop through a string character by character. A useless but illustrative example, using the preceding example string, is: for ($index = 0; $index < strlen($short_string); $index++) print($short_string{$index}); This simply prints: This string has 29 characterswhich is the string we started with. Finding characters and substringsThe next question you can ask your strings is what they contain. For example, the strpos() function finds the numerical position of a particular character in a string, if it exists. $twister = Peter Piper picked a peck of pickled peppers ; print( Location of p is . strpos($twister, p ) .
); print( Location of q is . strpos($twister, q ) .
); This gives us the browser output: Location of p is 8Location of q isThe q location is apparently blank because strpos()returns false if the character in ques- tion cannot be found, and a false value prints as the empty string. You should note that thestrpos()function is case-sensitive. Note10
If you are searching for cheap webhost for your web application, please visit MySQL5 Web Hosting services.