Friday, September 19, 2008

The substr() function

This function could be used to extract a certain part of the string.

Syntax: substr(string,start[,length]);

start – the starting position from where a sub-string should be extracted.
length – the number of characters the extracted string should contain.

Both start and length can also contain negative values.

A negative start parameter indicates that the position should be determined from the end of the string.

A negative length parameter would extract the certain number of characters from the end of the string.

If the length parameter is not specified, the rest of the string from the specified position would be returned.

Example inputs:

1.
$str1="This is a simple PHP program";
echo $str1;
echo "
";
echo substr($str1,17,3);
Here,the function returns the three characters after position 17 in $str1.

2.
$str1="This is a simple PHP program";
echo $str1;
echo "
";
echo substr($str1,-17);

3.
$str1="This is a simple PHP program";
echo $str1;
echo "
";
echo substr($str1,-17,-3);

Example outputs:

1.
This is a simple PHP program PHP
2.
This is a simple PHP program imple PHP program
3.
This is a simple PHP program imple PHP prog

No comments: