PHP Strings

In this article you will learn how to store and manipulate strings in PHP.

What is String in PHP

A string is a sequence of letters, numbers, special characters, and arithmetic values or combinations of all.

 <?PHP

    $name = "Jone Doe";
    echo "Your name is $name"; // OUTPUT:Your name is Jone Doe

    $name = "Jone Doe";
    echo 'Your name is $name'; // OUTPUT:Your name is $name

    $name = "Jone Doe";
    echo "Your name is ". $name; // OUTPUT:Your name is Jone Doe

    $name = "Jone Doe";
    echo 'Your name is '. $name; // OUTPUT:Your name is Jone Doe

?>

Calculating the Length of a String

The strlen() function is used to calculate the number of characters inside a string. It also includes the blank spaces inside the string.

<?php

$my_str = 'Welcome Message';
echo strlen($my_str);
 // OUTPUT: 15

?>

Counting Number of Words in a String

str_word_count() counts the word from the string.

<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
 
echo str_word_count($my_str);
 // OUTPUT: 9
?>

Replacing Text within Strings

The str_replace() replaces all occurrences of the search text within the target string.

<?php

$my_str = 'If the facts do not fit the theory, change the facts.';
echo str_replace("facts", "truth", $my_str);
 
//OUTPUT: If the truth do not fit the theory, change the truth.

?>

Reversing a String

The strrev() is used to reverse the string.

<?php
$my_str = 'You can do anything, but not everything.';
 
echo strrev($my_str);
//OUTPUT: .gnihtyreve ton tub ,gnihtyna od nac uoY
?>

Hope you understand!