PHP 7 Strings

String is an arrangement of characters. PHP has a good combination of built-in functions for string handling and for easily manipulation of strings.

Like by using php string built-in functions, we can -
  • a. Get length of string.
  • b. Reverse a string.
  • c. Convert the string in lowercase or uppercase.
  • d. Split a string.
  • e. Replace some part or character of a string.
  • f. Trim whitespaces from beginning and end of the string.
  • g. Convert the string in encoded form.
  • h. Get position of substring or a character in a string.

Lists of all built-in functions are given in PHP official website

http://php.net/manual/en/ref.strings.php

Some of the uses of built-in functions are -

echo()

Echo function is used to output string.

<?php
    $str1 = "Hello John, How are you?";
    echo ($str1);
?>




strlen()

This function is used to get length of a string.

<?php
    $str = 'India';
    echo strlen($str); // Output 5
?>

strcmp()

strcmp is used to compare two strings. It takes two strings as parameter.

<?php
    $str1 = "hello";
    $str2 = "Hello";
    $str3 = "";
    $str4 = "lo";

    echo strcmp($str1, $str2); 
    echo strcmp($str3, $str4); 
    echo strcmp($str1, $str4); 
?>

strpos()

This is used to find the first occurrence of a substring in a string.

<?php
    $str1 = "etutorialspoint";
    $str2 = "tutorial";
    $getpos = strpos($str1, $str2); 
    echo $getpos; // output 
?>

strtolower()

convert all strings to lowercase.

strtoupper()

convert all strings to uppercase

<?php
    $str1  = "Hello World";
    echo $strlowercase  = strtolower($str1 ); // Output hello world
    echo $struppercase = strtoupper($str1 ); // Output HELLO WORLD   
?>


Practice Exercises