Now list some String functions in PHP to handle and manipulate string in PHP.
All functions explained are inbuilt PHP functions also known as predefined string functions in PHP.
These functions are defined during creation of PHP.
sterlen() Length of String
sterlen() function is used to get the entire length of the string. If there is space in between two words then it will count that space as well.
Result:
5
Result:
12
str_word_count() -Word Count
str_word_count() function will give you the exact number of words that a string have.
Result:
4
Result:
4
strrev() -String Reverse
strrev() function is used to reverse the entire string.
Result:
!dlrow olleH
trim() -String Remove
Remove whitespace (or other characters) from the beginning and end of a string
"; $res=trim($text," "); echo $res; ?>
Output
These are a few words :) ... These are a few words :) ...
Another example
"; $without_space = rtrim($str,"im"); echo $without_space; ?>
I am using Trim I am using Tr
ltrim() => Remove whitespace (or other characters) from the beginning of a string
rtrim() => Remove whitespace (or other characters) from the end of a string
ucfirst()- Convert first letter into uppercase
convert first letter into uppercase of any string
John smith
strtoupper() -to upper case
This function converts the string in upper case
GOOD DAY MISS MOLLY!
strtolower() -Converts string to lowercase
convert whole string into lowercase
good day miss molly!
chr() -Return character from ASCII code
returns any character or letter and also special character from their equivalent ASCII Code
A
implode() -array to string
Implode function combine all array element with a string
Array
"; print_r ($arr); print " "; $string=implode(" ",$arr);
String- convert to string
Array
"; print_r ($arr); print " "; $string=implode(" ",$arr); print "
"; echo $string; ?> ?>
Output
Array Array ( [0] => 10 [1] => 20 [2] => 35 [3] => aaa [4] => 99 [5] => ccc ) 10 20 35 aaa 99 ccc
explode() -string to an array
Explode function split a string and return all value into an array.
STRING"; echo $s; //output print "
"; $arr=explode(",",$s); print_r($arr); ?>
Array- String to array conversion
STRING
Output
c cpp java php
strpos() -find the text position in string
strpos() function is used to find the particular text in a string.
If while searching in the string it founds the text, then it will give the position of that word in first search match or if the particular text is not found then it will return FALSE value.
Also first position of any character in string is 0 not 1.
Result:
19
str_replace() -Replace string
str_replace() function is used to replace some characters that are there in the strings.
Example:
Result
London is beautiful city