Home » Software » String Functions PHP

String Functions PHP

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).

String-Functions-PHP-2 String Functions PHP

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.

  1. printf – Output a formatted string
  2. sprintf – Saves a formatted string in a specified variable
  3. fprintf – Prints a formatted string to a file
  4. number_format  – Formats the specified numbers as strings
  5. wordwrap – Wraps a string to a given number of characters
  6. trim – Strip whitespace from a string
  7. strlen – Get string lenght
  8. explode – split a string by string
  9. htmlentities – Convert all applicable characters to HTML entities (Commonly used to protect website from XSS Injection)
  10. 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.

printf() Format

To controlling on how to format output string. PHP provides you with Format Specifiers. You can see List of printf() Specifier format below.

Specifier Example Format
b %b Integer in binary format
c %c ASCII character value for integer
d %5d Signed Integer
e %1.5e+1 Scientific Notation
f %.2f Float Number
o %o the argument is treated as an integer, and presented as an octal number.
s %s String of Characters
u %u Unsigned Integer
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

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.

String-Functions-PHP String Functions PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *

This site uses Akismet to reduce spam. Learn how your comment data is processed.