While developing php web application, often we received user input data as string, before inserting data into database table, we need to make sure data is correct and validated properly, that’s where all these string validation functions are required.
In this tutorial you will learn Php string Functions like substring, replace, converting string to uppercase, lowercase, getting string length count, string etc.
Some basic PHP String functions with examples that every Beginner should learn
Let's learn how to deal with string in Php, you will learn with following string function examples.
This built-in function can count total number of words in any given string
<?php echo str_word_count("We are learning PHP string function at WebTrainingRoom!"); // outputs 8 ?>
This built-in function can reverse a string, see the example below.
<?php echo strrev("I Love You"); // output would be "uoY evoL I" ?>
Use this function when you want to search a small string within a big string
<?php echo strpos("We are learning PHP string function at WebTrainingRoom!", "PHP"); // output would be 16 ?>
Note: this string search is case sensitive, for example in same string if you search for “php” instead of “PHP”, it will not find the string, so will not give any result.
Use this function when you want to replace a small string within a big string
str_replace("Find", "replace with", "big string");
<?php echo str_replace("We", "You", "We are the best!"); // output would be "You are the best!" ?>
strtolower()and String to upper
You can convert any string into uppercase and lowercase using built-in functions
<?php // to lowercase echo strtolower("This is my WORLD."); // to uppercase echo strtoupper("This is my WORLD."); ?>
this function returns the extracted part of any string, or an empty string, or FALSE on failure
<?php echo substr("How are you doing!",6) ?>
trim() Remove any spaces from both sides of a string, This function is very useful when you want any space to be removed from user input, situation like user name and password, we want to remove all whitespace from both side before saving or comparing values.
<?php echo trim(" I love my country "); ?>
Now you may come across situation when you want to remove whitespace value from just one side, either left or right side, but not from both side, in such situation you can use following functions.
ltrim()- ltrim removes whitespace from left side
rtrim()- rtrim removes whitespace from right side
You may be interested in reading following posts: