Monday, 22 August 2011

The strlen() function

The strlen() function

The strlen() function is used to return the length of a string.
Let find the length of a string:
PHP Code
echo strlen("Hello world!"); // 12
The output of the code above will be:

The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string).

The strpos() function

The strpos() function is used to search for a character/text within a string.
If a match is found, this function will return the character position of the first match. If no match is found, it will return FALSE.
Let see if we can find the string "world" in our string:
PHP Code
echo strpos("Hello world!","world"); // 6
The output of the code above will be:

The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character position in the string is 0, and not 1.

 echo strlen("Hello world!");
 echo "<br>"; //line break
 echo strpos("Hello world!","world");

No comments:

Post a Comment

Share on Tumblr