Basic String functions in PHP
How to use Basic String function in PHP
Similar to array built-in functions, there are some string built-in functions available in PHP to deal with strings. There are plenty of string functions in PHP which help in performing several manipulations on string data. In this article I will give you an idea on some basic string functions which are most frequently used in PHP scripts.
Here is the list...
1. Strlen Function
String
Length:This function gives you the length of the given string. Generally this function is used in validating user inputs, where the user is supposed to give specified length of characters.
Syntax:
Strlen(string);
Example:
<?php
$text = " e-Trainings";
print "Text length is =". strlen($text)."<br>";
?>
2. Strtoupper Function
strtoupper($string): is a string conversion function. Convert given
string into uppercase
Syntax
strtoupper($string)
Example:
<?php
$string="e-trainings";
print "<br>Upper=". strtoupper($string);
?>
3. Strtolower Function
strtolower(): is a string conversion function. Converts given string
into lowercase
Syntax
strtolower($string)
Example:
<?php
$string="e-trainings";
print "<br>Lower=". strtolower($string);
?>
4. Ucfirst Function
ucfirst(): is a string conversion function. Converts given string
first letter into uppercase. If any capital letter in the middle of
the word that will remain as it is.
Syntax
ucfirst($string)
Example:
<?php
$string="e-Trainings";
print "<br>ucfirst=". ucfirst($string);
?>output
E-Trainings
5. Substring Function
substring(): It returns a part of the string from given string
Syntax
substr ($string , startposition , No_of_characters);
Example:
substr ($string , 3 , 4);
<?php
$string="Welcome";
print "<br>Substring =". substr ($string , 0 , 3);
?>output
Substring = Wel
6. Strcmp Function
strcmp(); It compares two strings and returns a boolean value. This function we can be used to compare user input values and validate both are same or not.
Ex: comparing passwords
Syntax:
substr ($string , startposition , No_of_characters);
Example:
$boolan_value = strcmp("Cat", "cat") ;
Here I created one single PHP file with all the above functions which makes you run in one shot.
index.php
<!DOCTYPE html>
<html>
<body>
<?php
$string="weLcome";
print "<br>Upper=". strtoupper($string);
print "<br>Lower=". strtolower($string);
print "<br>Sentence =". ucfirst($string);
//from 3rd position reads 4 characters (0 is 1st)
print "<br>Substring =". substr ($string , 3 , 4);
$ans=strcmp("Cat", "cat") ;
if($ans == 0){
print( '<br> Both are same' );
}
else{
print(' <br> Both are not same');
}
print "<br>";
?>
</body>
</html>
output:
Upper=WELCOME
Lower=welcome
Sentence =WeLcome
Substring =come
Both are not same
Follow the Next Blog on Files in PHP
Comments
Post a Comment