Zend php 5 Certification exam tips-- strings Part II

· str[c]spn (string str2,string str2[,int start[,int length]])

· strspn () matches a string against a white list mask of allowed characters. Returns the length of the initial segment of the string that contains any of the characters specified in the mask.



echo strspn($string,$mask); // 6

· strcspn() is like strspn but takes a blacklist instead of a white list.

· Both strspn and strcspn accept two optional parameters that define the starting position and the length of the string to examine. i.e.:



echo strspn($string,$mask,1,4); //3

In the example above, strspn() will start examining the string from the second character(index 1) and continue for up to four characters.

· mixed str_replace(mixed search, mixed replace , mixed subject [,int &count])

using count:

$a=0; //initialize


echo $a; //3

if we wanna search and replace more than one needle at a time, we can pass first two args as arrays.

Example1: echo str-replace(array("hello","world"), array("bonjour","monde"),"hello world");

Example2: echo str_replace(array("hello,world),"bye","hello world");

In the first example the replacements are made based on array indices.

The first element of the search array is replaced by the first element of the replacement array, and the output is bonjour monde. In the second example, only the needle argument is an array resulting Bye Bye.

· Case insensitive str_replace = str_ireplace()

· If we need to replace a portion of a needle of which you already know the starting and ending points:

Mixed substr_replace(mixed string, string replacement, int start[,int length])

Substr_replace Replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. The result string is returned. If string is and array, then array is returned.

If start is positive, the replacing will begin at the startth offset into string.

If start is negative, begin at the startth char from the end of string.

If length is given and is negative, represents the number of chars from the end of the string at which to stop replacing. If not given, default is strlen($str).

Substr_replace examples:

Substr_replace($var,'abc'0) // all of $var with abc

Substr_replace($var,'abc',0,0 // right at the beginning.

· The combination of substr_replace and strpos is a powerful tool:


$name=substr_replace($user,' ', strpos($user,"@");

echo "hello ".$name; // hello danrah