Showing posts with label Substring functions in PHP. Show all posts
Showing posts with label Substring functions in PHP. Show all posts

Tuesday, September 23, 2008

The substr_replace() function

This function could be used to replace all or a portion of a string with another.

Syntax: substr_replace(string,sub-string,start[,length]);

sub-string – the string that replaces all or portion of the larger string.

start – the position in the original string from where the replacement should start.

If the start parameter is positive, the position is calculated from the beginning of the string.
If the start parameter is negative, the position is calculated from the end of the string.
A start parameter with the value zero would mean that the replacement should start from the first character of the string.

length – the number of characters that should be replaced.

A positive value for the length parameter indicates the number of characters to be replaced.
A negative value for the length parameter indicates the number of characters to be left at the end of the string.
Example input:
$str1="His name is James";
echo $str1;
echo "
";
echo $str2 = substr_replace($str1,"Her",0,3);
echo "
";
echo $str3 = substr_replace($str2,"Marie",-5);
echo "
";
echo substr_replace($str3," ",0,-5);
Example output:
His name is James
Her name is James
Her name is Marie
Marie

The substr_count() function

This function could be used to count the number of times a sub-string occurs within a given string.

Syntax: substr_count(string,sub-string[,start,length]);

sub-string- the string to be searched for
start – that position in the larger string from where the search should begin
length – length of the search from the starting position

If start and length parameters are not specified, substr_count() carries out search in the entire string.
Example input:
$str1="This is a simple PHP program";
echo $str1;
echo "
";
echo substr_count($str1,"PHP",3,20);
echo "
";
echo substr_count($str1,"PHP",3,10);
echo "
";
echo substr_count($str1,"i");
Example output:
This is a simple PHP program 1 0 3