Strings
A string of characters is probably the most commonly used data type when developing scripts, and PHP provides a large library of string functions to help transform, manipulate, and otherwise manage strings. We introduced the basics of PHP strings in Chapter 2. In this section, we show you many of the useful PHP string functions.
Length of a String
The length property of a string is determined with the strlen( ) function, which returns the number of eight-bit characters in the subject string:
integer strlen(string subject) |
We used strlen( ) earlier in the chapter to compare string lengths. Consider another simple example that prints the length of a 16-character string:
print strlen("This is a String"); // prints 16
Printing and Formatting Strings
In the previous chapter, we presented the basic method
for outputting text with echo
and
print
. Earlier in this chapter, we
showed you the functions print_r(
) and var_dump( ),
which can determine the contents of variables during debugging. PHP
provides several other functions that allow more complex and
controlled formatting of strings, and we discuss them in this
section.
Creating formatted output with sprintf( ) and printf( )
Sometimes, more complex output is required than can be
produced with echo
or print
. For example, a floating-point value
such as 3.14159 might need to be truncated to 3.14 in the output.
For complex formatting, the sprintf(
) or printf( )
functions are useful:
string sprintf (string format [, mixed args...]) |
Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.