PHP – String Manipulation
The most used functions for String Manipulation:
<?php
// ---------------------------------------------------------------
// String Operators
$a = "Hello";
$b = $a . " world!"; // Concatenation
echo $b; // outputs Hello world!
$x="Hello";
$x .= " world!"; // Concatenation Assignement
echo $x; // outputs Hello world!
// ---------------------------------------------------------------
// strlen - To return the lenght of the string, blank spaces included
echo strlen("Hello world!"); // the result is - 12 -
// ---------------------------------------------------------------
// strpos - To search for a specified character or text within a string.
// If a match is found, it will return the character position of the first match. If no match is found, it will return FALSE.
// The first character position in the string is 0, and not 1.
echo strpos("Hello world!","world"); // the result is 6
// ---------------------------------------------------------------
// trim - Strip (Remove) whitespace (or other characters) from the beginning and end of a string
$text = "Hello World";
echo $text; // Output: Hello World
echo '<br>';
echo trim($text, "Hello"); // Output: World
echo trim($text, "Hd"); // Output: ello Worl
// str_replace - Replace all occurrences of the search string with the replacement string
$phrase = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy = array("pizza", "beer", "ice cream");
echo $newphrase = str_replace($healthy, $yummy, $phrase);
// Output: You should eat pizza, beer, and ice cream every day
// ---------------------------------------------------------------
// substr - Returns the portion of string specified by the start and length parameters.
echo substr("abcdef", -1); // Output: "f"
echo substr("abcdef", -2); // Output: "ef"
echo substr("abcdef", -3, 1); // Output: "d"
// ---------------------------------------------------------------
// stripslashes - Remove backslashes
$str = "Is your name O\'reilly?";
echo stripslashes($str); // Output: Is your name O'reilly?
// ---------------------------------------------------------------
// strip_tags - Remove HTML and PHP tags
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo $text; // Output HTML formatted text
echo strip_tags($text); // Output plain text
// ---------------------------------------------------------------
// strtolower - Make a string lowercase
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtolower($str);
echo $str; // Output: mary had a little lamb and she loved it so
// ---------------------------------------------------------------
?>
All string functions at: http://www.php.net/manual/en/ref.strings.php