Like most programming language, PHP provide useful built-in string function. String Functions PHP allows you to manipulate entire string easily. It’s very important because you will spend so much of your time working with text in PHP. If you want more flexiblity on using string, PHP offers regular expressions (RegEx).
List of String Functions PHP
There are a number of String Functions PHP that allow you to output the string or number in a specified format. See the list of common used function below.
- printf – Output a formatted string
- sprintf – Saves a formatted string in a specified variable
- fprintf – Prints a formatted string to a file
- number_format – Formats the specified numbers as strings
- wordwrap – Wraps a string to a given number of characters
- trim – Strip whitespace from a string
- strlen – Get string lenght
- explode – split a string by string
- htmlentities – Convert all applicable characters to HTML entities (Commonly used to protect website from XSS Injection)
- implode – Join array elements with given string
Displaying Formatted String
Like most modern programming language (C, C++ and etc), PHP supports the printf() function for dealing with string formatting. Alternatively, you could use echo or print to display a string (but not formatted). The printf() function has a number of format to control the appearance of strings.
1 int printf (string $format [, mixed $args [, mixed $...]])
To controlling on how to format output string. PHP provides you with Format Specifiers. You can see List of printf() Specifier format below.
|b||%b||Integer in binary format|
|c||%c||ASCII character value for integer|
|o||%o||the argument is treated as an integer, and presented as an octal number.|
|s||%s||String of Characters|
|x||%x||Integer presented in hexadecimal representation in lowercase|
|X||%X||Integer presented in hexadecimal representation in uppercase|
Here’s an example of using String Functions PHP
1234 <?phpprintf( "Value of Pi to 1 decimals is %.1f <br/> \n", M_PI);printf( "Value of Pi to 3 decimals is %.3f <br/> \n", M_PI);?>
In example above, the control string %.1f and %.3f specifies the format we will use to represent the value of Pi. The output would be like.