Thursday, 7 July 2011

A comprehensive look at strings

Output a character from a string.
Eg:  $v="afss";
     echo $v[1];  will output 'f';
Find the string length
  strlen($string);
Find whether a string is contained within another string
  eg:   
     $email = 'USER@EXAMPLE.com';
      echo stristr($email, 'e'); // outputs ER@EXAMPLE.com

strstr- case sensitive stristr.
Index position of the character in the string
strpos($string, char) //from the beginning
strrpos()  // from the end

substr_count() //tells you how many times the search text occurs within the string

strpbrk() //searches a string for any of a list of characters
--------------------------------
Displays the rest of the string if any of the characters starting from the matched char.
$myString = “Hello, world!”;
echo strpbrk( $myString, “abcdef” ); // Displays ‘ello, world!’
echo strpbrk( $myString, “xyz” ); // Displays ‘’ (false)


strrev(); //string reverse
strtoupper();//every character is converted
strtolower();

Replacing text with strings
str_replace(search string, replacement string, $string);
substr_replace($string, "Replacement character", starting point, end point);

mb_substr($stringName ,starting point, length);  //get a portion of the string,  mb stands for MultiByte

explode("seperator" ,string) //CREATES AN ARRAY WITH EACH ELEMENT OF THE STRING(USING SEPERATOR)
eg:  $string = "1 2 3 4 5";
     $arr=explode(" " , $string);
     print_r($arr);

     implode or join  //opposite of explode
     eg: $arr= array("1","2","3","4","5");
     implode($arr," ")//the 2nd parameter is not mandatory(seperator)

     nl2br — Inserts HTML line breaks before all newlines in a string
     eg: echo nl2br("first line
                 second line
            third");

printf()//

// Displays “2 times 3 is 6.”
printf( “%d times %d is %d.”, 2, 3, 2*3 );

%d is the format string.
Remove white space
trim() removes white space from the beginning and end of a string
ltrim() removes white space only from the beginning of a string
rtrim() removes white space only from the end of a string

wordwrap();//If the string is too long, /n characters are inserted in between characters.

No comments:

Post a Comment