Find and Replace - PHP String FunctionsMarch 24, 2006 After working with PHP for some time, you are undoubtedly going to have work with string functions. If you've ever manipulated strings using Microsoft Excel, the process is pretty similar. Here I am going to look at how to isolate the domain name from an email address. This technique uses several PHP string functions to determine the overall length of the string, isolate everything before the "@" symbol, and then finally return everything after the @ symbol, which is the domain name. If you simply want to find out if a string of text contains a certain string, PHP makes it easy with the strpos function. The basic syntax will look something like this:
$string = "bobsmith@mydomain.com";
if ($pos === false) { So, this function is actually doing two things, it tells you whether or not a string is found within a variable, and then tells you the position the string starts at within that variable. The if...then statement determines if the string is found. If it is not found, there is no $pos value and thus "false" is returned. In our example though, we want to isolate the domain name from an email address. The pseudo-code would go something like:
1. Determine the length of the entire string So, here we go:
$string = bobsmith@mydomain.com $firstpart = strtok($string,"@"); //isolates string before @ symbol = bobsmith $char_count = $string_length - $firstpart_length; //21-9=12 $final_part = substr($string,$firstpart_length,$char_count); The last line takes the entire string, starts at the $firstpart_length character (9, or the @ symbol), and returns the number of characters determined by $char_count, which is 12. So, $final_part = "mydomain.com". There you have it! Technorati Tags: php string functions find and replace |