0
3.5kviews
Explain PHP string functions.
1 Answer
0
153views

PHP String Functions

  • A string is a collection of characters. String is one of the data types supported by PHP.
  • The PHP string functions are part of the PHP core. No installation is required to use these functions.
  • PHP has a vast selection of built-in string handling functions that allow you to easily manipulate strings in almost any possible way.
  • The most common string functions are as follows:

Function strlen() - To count the number of characters in a string strlen() function is used.

<?php
$str = "Ques10";
    echo "The length of string is:".strlen($str);
?>
// Displays: The length of string is:6

Function str_replace() - Replaces some characters in a string. str_replace() is case-sensitive, but we can also use its case-insensitive sibling str_ireplace() to avoid case-sensitiveness.

<?php
$oldstr = "The cat was black";
    $newstr = str_replace("black", "white", $oldstr);
    echo $newstr;
?>
// Displays: The cat was white

Functions strtoupper() & strtolower() - Converts a string into uppercase and lowercase respectively.

<?php
$str1 = "Example of uppercase Function.";
    $str2 = "Example of LOWERCASE Function.";
$case1 = strtoupper($str1);
$case2 = strtolower($str2);
echo $case1;
    echo "<br>"; 
    echo $case2;
?>
/* Displays: EXAMPLE OF UPPERCASE FUNCTION.
             example of lowercase function.*/

Function ucwords() - This function capitalized the first letter of each word.

<?php
$str = "example of PHP string function.";
    $cased = ucwords($str);
    echo $cased;
?>
// Displays: Example Of PHP String Function.

Function str_repeat() - It is used to repeat same string for a specific number of times.

<?php
$str = “Ques10 ”
    Echo “The Repeated string is:”.str_repeat($str , 4);
?>
// Displays: The Repeated string is: Ques10 Ques10 Ques10 Ques10

Function strrev() - This reverses a string.

<?php
echo strrev("Hello world!");
?>
// Displays: !dlrow olleH

Function str_word_count() - Counts the number of words in a string.

<?php
echo str_word_count("Hello world Example");
?> 
// Displays: 3
Please log in to add an answer.