note 104408 added to function.preg-match
| From: | milespickens+php at gmail dot com | Date: | Tue, 14 Jun 2011 04:44:15 +0000 |
| Subject: | note 104408 added to function.preg-match | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180504@lists.php.net to get a copy of this message | ||
My boss is trying to learn PHP, so sometimes I give him a mini-lesson. Here is what I shared with
him today about using preg_match.
I used to like doing my text manipulations in SQL but now I know how PHP is much faster and more
powerful. Any data manipulation needed, I save it for PHP functions. Here is an example of just
that.
<?php
////I need to display the City State and Primary phone number in another format.
////Here is an example of the data how it is stored in the database.
$data = "CYPRESS CA90638 7145552205625551898";
$pattern = '/(\D+?)\s+(\D{2,2})(\d+)\s+(\d{10,10}?)/';
///////////////with regular expressions you basically tell it what types of characters to look for
///////////////and how many of that type are in a sequence.
/////////////// \D is a non-digit, \d is a digit, \s is a space, and when I put ( ) parenthesis
around a
///////////////sequence I am matching that means I want that part of the string saved in an array.
preg_match($pattern,$data,$matches);
/////////////////$matches will be an array of my matched data.
///////////////So now, $matches[1] is the city, $matches[2] is the state,
/////////////// $matches[3] is the zip, and $matches[4] is the Primary phone number.
//Now I can make the address and phone number pretty,like
////CYPRESS, CA 90638
////(714) 555-5220
//And here is the last of the code. Here is where I
//use the result array to format my address and phone data.
$addr2 = $matches[1].', '.$matches[2].' '.$matches[3];
$phone = '('.substr($matches[4],0,3).')
'.substr($matches[4],3,3).'-'.substr($matches[4],6);
?>
----
Server IP: 69.147.83.197
Probable Submitter: 174.127.8.233
----
Manual Page -- http://www.php.net/manual/en/function.preg-match.php
Edit -- https://master.php.net/note/edit/104408
Del: integrated -- https://master.php.net/note/delete/104408/integrated
Del: useless -- https://master.php.net/note/delete/104408/useless
Del: bad code -- https://master.php.net/note/delete/104408/bad+code
Del: spam -- https://master.php.net/note/delete/104408/spam
Del: non-english -- https://master.php.net/note/delete/104408/non-english
Del: in docs -- https://master.php.net/note/delete/104408/in+docs
Del: other reasons-- https://master.php.net/note/delete/104408
Reject -- https://master.php.net/note/reject/104408
Search -- https://master.php.net/manage/user-notes.php