PHP String

When many characters written together in sequence, they create a php string. For example, India is a string. It is made up of i, n, d, i, a characters.

$string = "Welcome to Coding Bot";

A string may be compose of the given elements.

  • Letters – A string may be compose of small letters (a – z) or capital letters (A – Z).
  • Numbers – A string can contain any number from zero to 9.
  • Special Characters – A string can also contain special characters (@ # $% ^ &!). Escape sequence characters used to display special characters as a string.

Strings have great importance in web pages and databases. It is therefore necessary that a scripting language will provide you the capability to work with strings.

PHP provides support for working with strings. It is very easy to create strings in PHP and work with them. Also PHP gives you some built in functions to work with strings. Let us now see how you can create strings in PHP.

PHP String Functions

PHP provides approximately 100 built in string functions. Some of these functions are being explained by example below.

Length of a String

By the PHP strlen( ) function you can get the length of any string. As argument, you have a constant string or string variable pass in this string. This function returns the same number of characters you have in the string. This number includes spaces too.

Example

<?php
$string = "Welcome to Coding Bot";
echo strlen($string);   // output 21
?>

Count Number of Words in a String

By the PHP  str_word_count( )  function you can count the number of words in any string. As argument, you pass a string variable or constant string. This function returns you the number of words in that string. This is being explained by the example below.

Example

<?php
$string = "Welcome to Coding Bot"; 
echo str_word_count($string); // output 4
?>

Replace Text Within a String

With the PHP  str_replace( )  function replaces some words with some other words in a string and show that string. As argument, you pass this variable into the string variable or constant string and the word that you want to replaces from the string. The example below replaces the text “world” with “Dolly”:

Example

<?php
$string = "Welcome to Coding Bot"; 
echo str_replace("Bot","Tutorial",$string);    // output Welcome to Coding Tutorial
?>

Reverse a String

With the PHP  strrev( )  function you can display any string in a reverse order. As arguments, you pass the string that you want to display in the reverse order. This is being explain by the example below.

Example

<?php
$string = "Welcome to Coding Bot"; 
echo strrev($string); // output toB gnidoC ot emocleW
?>