A String is a sequence of characters, numbers, special characters or combination of all. You can create a string by enclosing (single quotation marks) of the string characters.
For example –
$str = "Hello World!";
You can also use double quotes to enclosed a string characters.
However single and double quotes work differently. A string enclosed by single quotes is considered string literally. But is a string contains some variables then it represent variable value in a string quoted by double quotes.
PHP String Functions – Manipulating PHP Strings
How to calculate length of a sting
Strlen() – Strlen() function helps to find the number of characters inside a string. It also counts the blank spaces inside the string.
How to Count the number of words in a string
Str_word_count() – function counts the number of words in a string.
<?php $my_str = “Welcome to Share Query Tutorial Website”; Echo str_word_count($my_str); ?>
How to replace text within string
Str_replace() function is used to replace all occurence of text within a string by a target string.
For example –
<?php $str = “Welcome to the Share Query, Please Share your Query to get answer”; //display replace string Echo str_replace(“share”, “my”, $str); ?>
How to Reversing a String
Strrev() – function reverse a string.
<?php $my_str = 'You can do anything, but not everything.'; // Display reversed string echo strrev($my_str); ?>
Some important PHP string functions –
- strtolower() – Converts a string to lowercase letters
- strtoupper() – Converts a string to uppercase letters
- ucfirst() – Converts the first character of a string to uppercase
- ucwords() – Converts the first character of each word in a string to uppercase
- strstr() – Finds the first occurrence of a string inside another string
- substr() – Returns a part of a string
- trim() – Removes whitespace or other characters from both sides of a string