String Theory - Instant Paralysis
(Page 5 of 7 )
You can also search for specific patterns in your strings with regular expressions, via PHP's preg_match() function.
<?
$str = "johndoe@somedomain.com";
$pattern =
"/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/";
// returns true
echo preg_match($pattern, $str);
?>
You can also use the ereg() function to perform a regular
expression match,
<?
$str = "yo ho ho and a bottle of gum";
// returns true
echo ereg("bo*", $str);
?>
and the ereg_replace() function to perform a
search-and-replace operation.
<?
$str = "yo ho ho and a bottle of gum";
// returns "yo ho ho and a bottle of rum"
echo ereg_replace("gum", "rum", $str);
?>
If you need to perform substitution within a string, PHP also
has the str_replace() function, designed specifically to perform find-and-replace operations.
<?
$str = "...as Michael dropped into a crouch and came up under Frank's
punch, he swiveled to the side and kicked Frank in the spine, immediately
breaking one of Frank's vertebrae and rendering him paralyzed for life...";
// returns "...as Michael dropped into a crouch and came up under John's
punch, he swiveled to the side and kicked John in the spine, immediately
breaking one of John's vertebrae and rendering him paralyzed for life..."
echo str_replace("Frank", "John", $str);
?>
Next: A Quick Trim >>
More PHP Articles
More By Vikram Vaswani, (c) Melonfire