PHP String Functions

0
2280

Today we will be seeing some important string functions in this PHP String Functions Tutorial.

  • String is a sequence of characters enclosed in single quotes or double quotes. For example “My name is XYZ.” is a string.
  • Various operations can be done on strings such as finding a substring in a string, calculating length of a string, encrypting a string, decrypting a string etc.
  • Some string operations are daily required and some needs a lot of code to achieve the desired output. For example finding length of a string can be used in almost any string manipulation and tasks like encrypting a string, decrypting a string requires a lot of code.
  • Functions for such tasks are inbuilt in PHP. We just have to call these functions in our program.
  • We know, built –in functions are the functions already written for the language and which can be directly used by calling them in our programs.
  • So let us see some of the inbuilt functions used for string manipulation.
  • To get demonstration of the functions given below, create a new folder named string in the htdocs folder in xampp folder. Now open a new notepad++ document and save it as index.php in the newly created string folder.
  • Write the code for every example given below in index.php file and see its output by opening the browser and typing localhost/string in the address bar.
  • Some of the string functions:
    1. echo():
      • The echo() function is used to display one or more strings.
      • You can use it to display any string or variables.
      • The string in this function can be enclosed in single quotes or double quotes.
      • The parentheses are optional. i.e. it doesn’t matter even if you don’t specify the parameters.
      • Syntax of echo() function is:
      • or

    2. strlen():
      • The strlen() function is used to find out the length of the given string.
      • It counts every character in a string, even a blank space.
      • Syntax of strlen() function is given below:
      • Example of echo() and strlen():
      • Write the following code to demonstrate echo() and strlen() in the index.php file:

        • In the above code we have called the echo statement with parenthesis as well as without parenthesis.
        • Next the strlen() function counts all characters in the string given and returns its length as 32.
        • The output is shown below:
        • echo_strlen_func_output
          fig 1

    3. strpos():
      • The strpos() function is used to search for the position of another string in a given string.
      • If found the match it returns the position of the starting letter of the string that is to be searched in the given string otherwise it returns false.
      • Syntax of strpos() function is:
      • The characters are always counted from 0 onwards i.e. the first character position in the string is 0.
    4. substr():
      • The substr() function is used to extract only the required part from an existing string.
      • Syntax of substr() function is:
      • It takes 3 parameters, an existing string, the starting position from where to start extracting the string and the length up to where to extract the string.
      • The parameter length can be optional.
      • Example of strpos() and substr():
      • Write the following code to demonstrate strpos() and substr() in the index.php file:

        • Here, we have used strpos() function to find out the position of the word success in the given string.
        • The control starts counting the positions from 0 and not from 1.
        • Next the substr() function is used to extract the string from position 0 up to length 9 from the given string God bless you!. It returns God bless.
        • If you don’t provide length in the substr() function it will return the remaining string from the given position, as done in the statement . This will return the string bless you!, which starts from position 4 in the original string.
        • The output is given below:
        • strpos_substr_func_output
          fig 2

    5. strtolower():
      • The strtolower() function converts the uppercase letters in a given string to lowercase.
      • It’s syntax is given below:
    6. strtoupper():
      • The strtoupper() function converts the lowercase letters in a given string to uppercase.
      • It’s syntax is given below:
      • Example of strtolower() and strtoupper():
      • Write the following code to demonstrate strtolower() and strtoupper() in the index.php file:

        • Here, in the above code we have demonstrated the strtolower() and strtoupper() functions.
        • Output is shown below:
        • strtolower_strtoupper_func_output
          fig 3

    7. trim();
      • The trim() function is used to erase the predefined characters and whitespaces from both the sides of a string.
      • Predefined characters are characters like \0, \n, \t etc.
      • Syntax of trim() function is:
      • It takes 2 parameters a string that is to be trimmed and which characters are to be erased from the string.
      • The second parameter is optional. In the absence of second parameter the function trim() erases all the extra spaces at both sides of the string.
    8. wordwrap():
      • The wordwrap() function is used to cut the given string after it reaches to a specific length.
      • It is similar to the wordwrap operation in notepad.
      • Syntax of wordwrap() function is:
      • The wordwrap() function has 4 parameters among which last two are optional.
      • The parameter string is the string to be wrapped.
      • The parameter width is the maximum number of characters one row can contain.
      • The parameter break is the tag or character using which the line can be broken. Examples of characters that can be used to break a line are html break tag or \n.
      • The parameter cut if is set to true, wraps the string before or at the specified position. So that the word larger than the given width is broken apart.
      • Example of trim() and wordwrap():
      • Write the following code to demonstrate trim() and wordwrap() in the index.php file:

      • In the above code, we have demonstrated the trim() and wordwrap() functions.
      • In the string stored in variable $s2 we have given 2 tab spaces before the string, but still when the string is displayed using trim() function, all the spaces before and after the string are erased.
      • This trim() function is more useful to erase the both side spaces of the input given by the user.
      • When we tried to wrap the string in variable $s3 according to width 8, the string is broken using html brake tag.
      • The output is shown below:
      • trim_wordwrap_func_output
        fig 4

9. strcmp():

  • The strcmp() function is the case-sensitive function used to compare two strings.
  • When 2 strings given in strcmp() function are equal, it returns zero (0).
  • It returns value less than zero if the first string is less than the second string and it returns value greater than zero if the first string is greater than second string.
  • It gives such results because it compares the ASCII values of the characters of the string to one another.
  • Syntax of strcmp() function is:

10. md5():

  • The md5() function is used to calculate Message-Digest Algorithm hash of a string.
  • I mean using the md5 algorithm, the given string is converted to a 32 bit hexadecimal format.
  • The md5() function uses RSA Data Security, Inc. MD5-Message Digest Algorithm for conversion of the string.
  • Syntax of md5() function is given below:
  • The md5() function has 2 parameters of which the second in optional.
  • The parameter string is the string that is to be converted to the hexadecimal or binary format.
  • The optional parameter raw has 2 values, true and false.
  • If it is given as true, then the string is converted to a 16 character binary format.
  • And if raw parameter is given as false, then the string is converted to a 32 character hexadecimal number.
  • By default its value is false.
  • Example of strcmp() and md5():
  • Write the following code to demonstrate strcmp() and md5() in the index.php file:

    • In the above code we have compared strings “welcome” and “Welcome” using strcmp() function.
    • This function compares the ASCII values of each character in the strings and outputs the value accordingly.
    • In the above example the first string is greater than the second string because the ASCII value of ‘w’ is greater than the ASCII value of ‘W’.
    • Next the string “Richa123” is converted to its binary as well as hexadecimal equivalent using the md5() function.
    • The binary value is 16 characters long and the hex value is 32 characters long.
    • This can be used to make some values non-understandable. For example passwords.
    • The output of both strcmp() and md5() is shown below:
    • strcmp_md5_func_output
      fig 5

11. explode():

  • The explode() function is used to break a string into number of substrings and these are stored into an array.
  • Syntax of explode() function is given below:
  • It takes 3 parameters as follows:
  • The parameter string_separator is the delimitor used to separate the string. For example a blank space.
  • The parameter string is the string that is to be broken down into substrings.
  • The parameter limit is an optional parameter.
  • If it is a positive number, then the array formed contains that many number of strings and the rest of the remaining strings are contained in the last element.
  • If it is a negative number, then all components except the last element are returned.
  • If it has value zero (0), then it is treated as 1.

12. implode():

  • The implode() function is used to reverse the work done by explode() function.
  • It means implode() function is used to join the array elements into a string.
  • Syntax of implode() function is given below:
  • It has 2 parameters of which first one is optional and second is mandatory.
  • The parameter string_separator is to specify as to use which delimitor to separate the substrings in the string.
  • The parameter array is the array whose elements will be joined into a single string.
  • Example of explode() and implode():
  • Write the following code to demonstrate explode() and implode() in the index.php file:

    • Here, in the above example a string “You can WIN!” is broken down and stored in an array using the explode() function.
    • The print_r() function is mainly used to print arrays in the array format itself i.e. along with the index and its value.
    • So we have used print_r() function to print the output of explode function.
    • Next we have an array pointed by $arr variable. We want the array elements to be joined into a single string. This is done using implode() function.
    • The output is shown below:
    • explode_implode_func_output
      fig 6

  • Some more string functions:
  • String Function Syntax Example Description
    addcslashes() addcslashes(string,characters); $str=addcslashes(“What is your AC id”,’C’); The function addcslashes() will add a backslash before the character ‘C’ and return the string as “What is you’re A\C id”.
    convert_uudecode() convert_uudecode(encrypted string); $enstr=”C@#45Fg”;
    $str=convert_uudecode($enstr);
    The function convert_uudecode() decodes the encrypted form of a string again to the original string.
    convert_uuencode() convert_uuencode(string); $str=”Hello Everybody”;
    $enstr=convert_uuencode($str);
    The function convert_uuencode() encodes the given original string to an encrypted format.
    str_replace() str_replace(find,replace,string,count); echo str_replace(“Hello”,”Hi”,”Hi Dear”); This function is used to replace the found strings given in the string. The parameter find contains the string(s) to be searched, replace contains the string(s) to be replaced, string is the given string and count counts the number of replacements done.
    str_split() str_split(string,length); $str=”You are Welcome”;
    print_r(str_split($str,3));
    This function splits a string into small substrings according to the length given and stores it into an array similar to explode() function. By default it takes length 1.
    str_word_count() str_word_count(string); $w=str_word_count(”How many words are there in the given string?”); This function counts the number of words in the given string.

    These are some of the more string functions, there are many such functions.

    Thus we studied some of the important string functions that will be useful in string manipulations in this PHP String Functions tutorial.

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here