Monday, 5 August 2019

Useful strings function in PHP

Here are detailed working on useful strings functions in PHP

FunctionDescription and working
strlen()The PHP strlen() function returns the length of a string.
The example below returns the length of the string “john”
Example
<?php
echo strlen(“John”);
?>
Output
4
Chr()Converts an ASCII value to its equivalent character
Example
The ASCII value 64 is the @ symbol
<?php
$str = chr(046);
echo(“the value are 1 $str 2”);
?>
Output
the value are 1 & 2
strrev()It reverses the string
Example
<?php
echo strrev(“John”);
?>
Output
nhoJ
Substr()The substr() function returns a part of a string
substr(string,start,length)
start: where to start in the string
Length: length of the returned string. Default is to the end of the string
This is optional. If you miss it out, you’ll grab all the characters to the end of the string.
Example
<?php
substr(john,1,3) ;
?>
Output
joh

str_word_count()The str_word_count () function tells you how many words a string has.
Example
<?php
str_word_count(“how are you”);
?>
Output
3
str_replace()The str_replace() function in PHP allows you to replace one string with another.
str_replace( $look_for, $change_to, $search_text );
Example
<?php
str_replace(“John”,”Matt”, “John is absent”  );
?>
Output

Matt is absent


strops()The PHP strpos() function searches for a specific text within a string.
If the function can find a search match, then it will return the position of the firstmatch. However, if it can’t find a match it will return false
strpos (‘string’, ‘match_pattern’, [offset])
The optional offset parameter tells the function to start looking for the match after the offset-th character in the string. The value returned by the function still indicates the position of the first match relative to the entire string.
Example
<?php
str_replace(“today is monday”,”mon” );
?>
Output
8
In this example, the match occurs at the 9 place string, hence the function returns 8 as numbering starts from 0

0 comments:

Post a Comment