Strings in PHP (part-2)

October 26, 2015  By Harish Kumar  Share

Show full series till now

Go Back To Last Tutorial

In this tutorial, we will study about strings and operations upon strings. Due to long length of this section, I have put this in two parts. This is second part. You may read it without reading part 1, but I will recommend you to read both parts for best understanding. First take a preview:


  1. Creating, Accessing and using with $, {} and strlen()
  2. Searching
    • strstr()
    • strpos() and strrpos()
    • substr_count()
    • strpbrk()
  3. Replace string with str_replace(), substr_replace(), strtr()
  4. Dealing With Uppercase and Lowercase
    • strtolower()
    • strtoupper()
    • ucfirst()
    • lcfirst()
    • ucword()
  5. Case insensitive functions for all above


  1. Formation String with printf(), Padding the output, Number Precision
  2. Trimming Strings with trim(), ltrim(), and rtrim()
  3. Padding Strings with str_ pad(), STR_PAD_RIGHT, STR_PAD_LEFT, STR_PAD_BOTH
  4. Wrapping Lines of Text with wordwrap()
  5. Formatting Numbers with number_format()

1) Formation String


printf() is very powerful functions that you can use to format strings in all sorts of different ways. printf() takes a string argument called a format string, usually followed by one or more additional arguments containing the string or strings to format. It then outputs the result. The format string contains ordinary text intermingled with one or more conversion specifications. Each conversion specification requires an additional argument to be passed to printf(), and it formats that argument as required and inserts it into the format string. The resulting formatted string is then displayed. Conversion specifications always start with a percent (% ) symbol. This probably sounds a little overwhelming at first glance, so here’s a simple example to illustrate the point:

  1. <?php
  2. // Displays “Pi rounded to a whole number is: 3”
  3. printf( “Pi rounded to a whole number is: %d”, M_PI );
  4. ?>

In this example, “Pi rounded to a whole number is: %d” is the format string, and the “%d” within the string is a conversion specification. In this case, the conversion specification tells printf() to read an additional argument and insert it, formatted as a whole decimal number, into the format string. The additional argument is the PHP constant M_PI, which represents an approximation of pi to a number of decimal places (14 by default). So the net result of the function call is to print the format string with the “%d” replaced by the value of pi rounded to a whole number.

More type specifier:

Type SpecifierMeaning
bTreat the argument as an integer and format it as a binary number.
cTreat the argument as an integer and format it as a character with that ASCII
dTreat the argument as an integer and format it as a signed decimal number.
eFormat the argument in scientific notation (for example, 3.45e+2).
fFormat the argument as a floating-point number, taking into account the
current locale settings (for example, many European locales use a comma for
the decimal point, rather than a period).
FFormat the argument as a floating-point number, ignoring the locale
oTreat the argument as an integer and format it as an octal number.
sFormat the argument as a string.
uTreat the argument as an integer and format it as an unsigned decimal
xTreat the argument as an integer and format it as a lowercase hexadecimal
XTreat the argument as an integer and format it as an uppercase hexadecimal
%Display a literal percent (% ) symbol. This doesn’t require an argument.

Padding the output:

You can add characters to the left (by default) or the right of the formatted argument in order to pad it out to a fixed width. This is useful if you want to add leading zeros to a number, or horizontally align many strings by padding with spaces.

  1. <?php
  2. // Displays “000123”
  3. printf( “%06d
  4. ”, 123 );
  5. // Displays “004567”
  6. printf( “%06d
  7. ”, 4567 );
  8. // Displays “123456”
  9. printf( “%06d
  10. ”, 123456 );
  11. ?>

Number Precision:

When displaying floating-point numbers with the f or F type specifier, you can use a precision specifier to
indicate how many decimal places to round the number to. To add a precision specifier, insert a period
( . ), followed by the number of decimal places to use, before the type specifier:

  1. <?php
  2. // print “123.456700” (default precision)
  3. printf( “%f
  4. ”, 123.4567 );
  5. //print “123.46”
  6. printf(“%.2f
  7. ”, 123.4567 );
  8. // print “123"
  9. printf(“%.0f
  10. ”, 123.4567 );
  11. // print “123.4567000000”
  12. printf(“%.10f
  13. ”, 123.4567 );
  14. ?>

You can use a padding specifier with a precision specifier, in which case the entire number is padded to
the required length (including the digits after the decimal point, as well as the decimal point itself):

  1. ?php
  2. // Displays “123.46”
  3. printf( “%.2f
  4. ”, 123.4567 );
  5. // Displays “000000123.46”
  6. printf( “%012.2f
  7. ”, 123.4567 );
  8. // Displays “ 123.4567”
  9. printf( “%12.4f
  10. ”, 123.4567 );
  11. ?>

2) Trimming String:

Sometimes we don't want any space before or after or both sides of the string. In such cases we trim the string by using these functions:

trim()removes white space from the beginning and end of a string
ltrim()removes white space only from the beginning of a string
rtrim()removes white space only from the end of a string

For example check the result of this example:

  1. <?php
  2. echo trim(" harish );
  3. echo ltrim(' harish ');
  4. echo rtrim(' harish ');
  5. ?>

3) Padding Strings:

You’ve already seen how you can use printf() to add padding to the beginning or end of a string. However, PHP features a dedicated function, str_pad(), that is both more flexible than the printf() approach and easier to work with.

To use str_pad(), pass the string to be padded, and the desired width of the final string. The function returns the string padded on the right using space characters (by default):

  1. <?php
  2. echo '<pre>';
  3. echo str_pad( "Hello, world!", 20 ); // Displays "Hello, world! "
  4. echo '</pre>';
  5. ?>

To pad using characters other than space, pass a string to use as an optional third argument. Note that this can be either a single character or a string of characters; in the latter case, the string is repeated as needed to pad out the input string:

  1. <?php
  2. // Displays “Hello, world!*******”
  3. echo str_pad( “Hello, world!”, 20, “*” ) . “\n”;
  4. // Displays “Hello, world!1231231”
  5. echo str_pad( “Hello, world!”, 20, “123” ) . “\n”;
  6. ?>

You can also make str_pad() add padding to the left of the string, or to both the left and the right of the string. To do this, pass an optional fourth argument comprising one of the following built-in constants:

STR_PAD_RIGHTto pad the string on the right (the default setting), left-aligning the string
STR_PAD_LEFTto pad the string on the left, right-aligning the string
STR_PAD_BOTHto pad the string on both the left and the right, centering the result as much as possible

For example:

  1. <?php
  2. // Displays “***Hello, world!****”
  3. echo str_pad( “Hello, world!”, 20, “*”, STR_PAD_BOTH ) . “\n”;
  4. ?>

4) Wrapping Lines:

Sometimes you have to write long text like email or essay. You want proper line break for different widths. The function wordwrap() does this work. You can limit number of character in this function. Lets see an example first:

  1. <?php
  2. $myString = "this is my string
  3. which is very long.
  4. it is containing five lines
  5. and a number of white
  6. spaces";
  7. echo wordwrap ( $myString);
  8. echo "
  9. ";
  10. echo wordwrap ( $myString, 40);
  11. echo "
  12. ";
  13. echo wordwrap ( $myString, 40, “
  14. ” );
  15. ?>

Notice the result yourself by opening console of your browser or source page and also notice the result for different sentences and different values of second argument (other than 40 like 10, 15, 20 etc.).

5) Formatting Numbers:

Function number_format() is used to format a number. It can take one, two or four arguments.

  1. First arguments is number which has to be formatted
  2. Second argument is the number of decimal places
  3. Third argument is the character with which decimal numbers are to be separated
  4. Fourth number is with which number is to be formatted

Understand by this example:

  1. <?php
  2. $myNumber = 12344555.3453;
  3. // display 1,23,44,555.3453
  4. echo number_format($myNumber);
  5. echo "
  6. ";
  7. // display 1,23,44,555.34
  8. echo number_format($myNumber,2);
  9. echo "
  10. ";
  11. // display 1 23 44 555,3453
  12. echo number_format($myNumber,2,',',' ');
  13. echo "
  14. ";
  15. ?>

If you can not understand anything then ask without any hesitation. In next tutorial, we will study about array and its properties.

Click on banner below to Learn: PHP with Laravel for beginners - Become a Master in Laravel

About Harish Kumar

Harish, a technical core team member at with five year experience in full stack web and mobile development, spends most of his time on coding, reading, analysing and curiously following businesses environments. He is a non-graduate alumni from IIT Roorkee, Computer Science and frequently writes on both technical and business topics.

Related Articles

PHP stands for PHP: Hypertext Preprocessor. PHP is known as a server side scripting and interpreter language for web ...
Introduction to PHP
In this tutorial, we will study about conditional statements (if else statements and switch statements). These statem...
Conditional statements in php
In this tutorial, we will study about strings and operations upon strings. Due to long length of this section, I have...
Strings in PHP (part-1)

Full-Stack Web Development with React

Best Udemy Courses

Top Posts

Recent Posts

The Complete Web Developer Course - Build 25 Websites


Subscribe now and get weekly updates directly in your inbox!

Any Course on Udemy in $6 (INR 455)

Development Category (English)300x250