HighlyStructured.com is a blog website run by Mike D'Agostino about search engine positioning, online marketing, php/MySQL, tae kwon do, and various other topics.

Find and Replace - PHP String Functions

March 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";
$find = "smith";
$pos = strpos($string, $find);

if ($pos === false) {
   echo "The string was not found";
} else {
   echo "The string was found at position $pos";
}

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
2. Find the "@" symbol position in the string
3. Split the string into two parts, the first part existing before the @ symbol, the second after the @ symbol
4. Determine the length of the first part
5. Subtract the length of the first part from the entire length of the string to determine the starting point of the domain name
6. Isolate the domain name

So, here we go:

$string = bobsmith@mydomain.com
$string_length = strlen($string); //returns 21

$firstpart = strtok($string,"@"); //isolates string before @ symbol = bobsmith
$firstpart_length = strlen($firstpart); //returns 8
$firstpart_length++; //add 1 to account for @ symbol = 9

$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:       

Recent Articles

Topics

Archive

Other Blogs of Interest