Tuesday, June 26, 2012

PHP Learning - Working with Data(4)

PHP provides many built-in functions for manipulating strings. When you want to remove the leading or trailing spaces, you can use the following statement:
$string = trim($string) ; # removes leading & trailing spaces
$string = ltrim($string) ; # removes leading spaces
$string = rtrim($string) ; # removes trailing spaces

PHP can also help you split a string into words. The general
form of this function is as follows:
str_word_count(“string”,format);
In this expression, format can be 1, meaning return the words as a numeric
array; or 2, meaning return the words as an array where the key is the position
of the first character of the word. It may be confusing to you at this point, I will explain array in detail in the future of my php lesson.
To give you an example here:
$string = “Counting Words”;
$number of words = str_word_count($string);
$word1 = str_word_count($string,1);
$word2 = str_word_count($string,2);

if we echo $word1, we get:
$word1[0] = Counting
$word1[1] = Words
if we echo $word2, we get:
$word2[0] = Counting
$word2[9] = Words


View the original article here

No comments:

Post a Comment