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

No comments: