Strings in PHP (part-1)

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. First take a preview:

Part-1:

  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

Part-2

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

Why do I need to learn about strings?

In web development, we have to get data from user. Most of times, it is in form of string (in text). So, for security purpose we have to filter the data. So, we need the knowledge of string operations.

1) Creating and Accessing

As you know already, we define string by writing text within single quotation mark or in double quotation mark and assigning it to a variable:

$string = 'string'; or $string = "string";

Now we will study some more about string. Any variable names within the string are parsed and replaced with the variable’s value. We can place variables directly in string like this:

  1. <?php
  2. $myname = 'harish';
  3. // this will give output ==> Hey! I am harish
  4. echo 'Hey! I am $myname';
  5. //for changing the line
  6. echo '
  7. ';
  8. //some more complicated example
  9. $cat = "cat";
  10. // {} covers a variable
  11. // this will give you output ==> these are cats
  12. echo 'these are {$cat}s';
  13. ?>

In strings, we have some escape characters which are used to print space. NOTE: Special variable can not be escaped in single quotation. They are only for double quotation.

  1. <?php
  2. $myname = 'harish';
  3. // \n is new line character
  4. /* here you will get output like this in browser
  5. string harish
  6. but when you will inspect element
  7. you will find like this:
  8. string
  9. harish
  10. because html escapes extra spaces
  11. but they are useful in PHP
  12. */
  13. echo "string\n $myname";
  14. ?>
Escape characters in PHP

Finding length of string:

The length of string is found by function strlen(). It takes a string as argument and returns the length of string.

  1. <?php
  2. $myname = 'harish';
  3. // return 6
  4. echo strlen($myname).'</br>';
  5. // return 14 (includes spaces)
  6. echo strlen('it is a string');
  7. ?>

NOTE: It is interesting that you can access characters in the string. Just try to print $myname[0], $myname[1] and so on up to 5 and notice the result. You will get 'h', 'a', 'r', 'i', 's', 'h'.

2) Searching Strings:

The functions for find string take two arguments, first string in which we have to find and another the text which has to find. If text is not found in string then these functions return false. We have following function for searching string:

FunctionsFunction Description
strstr()If the text is found, strstr() returns the portion of the string from the start of the found text to the end of the string.
strpos()It is used to find out from starting exactly where a string of text occurs within another string and return position
strrpos()It is similar to strpos() but search from end.
substr_count()It count the number of occurrence of the text in the string
strpbrkCheck if any of the letter of text is present in the string and returns the string after that letter.

NOTE: These all functions (except substr_count()) works until first occurrence and terminates after that. For example if I search for 'h' in 'harish' then strstr('harish','h') will return first 'h' and then will terminate.

For more clarity, look at this example:

  1. <?php
  2. $string = "This is a @str string for a search";
  3. // this will return search
  4. // the part of word starting with sea
  5. echo strstr($string, 'sea').'</br>';
  6. // this will return earch
  7. // the part of word starting with ear
  8. echo strstr($string, 'ear').'</br>';
  9. // this will return 8
  10. // it is postition fo first 'a'
  11. // position starts from 0, not 1
  12. echo strpos($string, 'a').'</br>';
  13. // this will return 30
  14. // it is position of last 'a'
  15. echo strrpos($string, 'a').'</br>';
  16. // this will return 3
  17. // number of 'a'
  18. echo substr_count($string, 'a').'</br>';
  19. // this will return @str string for a search
  20. // string after @ (includeing @)
  21. echo strpbrk($string, '@').'</br>';
  22. ?>

3) Replace string:

FunctionsDiscription
str_replace()replaces all occurrences of the search text within the target string
substr_replace()replaces a specified portion of the target string with another string
strtr()replaces certain characters in the target string with other characters

Now take a look on each function one by one:

str_replace()

The function takes three arguments: the search string, the replacement string, and the string to search
through. It returns a copy of the original string with all instances of the search string swapped with the
replacement string.Here’s an example:

  1. <?php
  2. $myString = "It was the best of times, it was the worst of times,";
  3. // Displays "It was the best of bananas, it was the worst of bananas,"
  4. echo str_replace( "times", "bananas", $myString );
  5. ?>

If you want to know how many times the search string was replaced, pass in a variable as an optional
fourth argument. After the function runs, this variable holds the number of replacements:

  1. <?php
  2. $myString = “It was the best of times, it was the worst of times,”;
  3. // Displays “It was the best of bananas, it was the worst of bananas,”
  4. echo str_replace( “times”, “bananas”, $myString, $num ) .
  5. ”;
  6. // Displays “The text was replaced 2 times.”
  7. echo “The text was replaced $num times.
  8. ”;
  9. ?>

substr_replace():

Whereas str_replace() searches for a particular string of text to replace, substr_replace() replaces
a specific portion of the target string. To use it, pass three arguments: the string to work on, the
replacement text, and the index within the string at which to start the replacement. substr_replace()
replaces all the characters from the start point to the end of the string with the replacement text,
returning the modified string as a copy (the original string remains untouched).

This example shows how substr_replace() works:

  1. <?php
  2. $myString = “It was the best of times, it was the worst of times,”;
  3. // Displays “It was the bananas”
  4. echo substr_replace( $myString, “bananas”, 11 ) .
  5. ”;
  6. ?>

You can see that the preceding code has replaced all of the original text from the character at index 11 onwards with the replacement text (“bananas” ). If you don’t want to replace all the text from the start point to the end of the string, you can specify an optional fourth argument containing the number of characters to replace:

  1. <?php
  2. $myString = “It was the best of times, it was the worst of times,”;
  3. // Displays “It was the best of bananas, it was the worst of times,”
  4. echo substr_replace( $myString, “bananas”, 19, 5 ) .
  5. ”;
  6. ?>

strtr():

You can also use strtr() to replace strings with strings, rather than characters with characters. To do
this, pass just two arguments: the string to work on, and an array of key/value pairs, where each key is
the string to search for and each corresponding value is the string to replace it with. More on arrays in the
next tutorial.

4) Dealing With Uppercase and Lowercase

These all functions take one argument only, i.e. string. Put string and see results yourself.

FunctionDescription
strtolower()make all letters of string lowercase
strtoupper()make all letters of string uppercase
ucfirst()make first letter of string uppercase
lcfirst()make first letter of string uppercase
ucword()makes the first letter of each word in a string uppercase

5) Case insensitive functions

These are functions which do not consider case of letters during operations:

FunctionCase-Insensitive Equivalent
strstr()stristr()
strpos()stripos()
strrpos()strripos()
str_replace()str_ireplace()

Due to length of this tutorial, it may be some (or more boring and irritated) . Thank you for keeping patience. If you can not understand anything then ask without any hesitation. In next tutorial, we will continue our study about next 5 operations on strings.

next tutorial



ReactJS with Redux Online Training by Edureka

About Harish Kumar

Harish, a fullstack developer at www.lyflink.com 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 non-technical 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)

Complete Python Bootcamp: Go from zero to hero in Python 3

Top Posts

Help Dad unlock new skills this summer in just $10 on Udemy

Development Category (English)300x250

The Complete Web Developer Course - Build 25 Websites

Meet on Twitter

Subscribe

Subscribe now and get weekly updates directly in your inbox!

Best Video Courses