Page 1 of 1

Get a specific list of postcodes with MySQL Like Operator

Posted: Fri May 03, 2013 6:15 am
by nita
Hi everyone.

I have list of postcodes. And what i'm trying to do is get a listing of similar poscodes only.

My Code:

Code: Select all

$postcode1 = ereg_replace('[^A-Za-z]', '', $postcode);

SELECT * FROM coverparked WHERE postcode LIKE '$postcode1%' ORDER BY postcode
So then $postcode1 strips all number from postcode, so for example E16 is strpped down to E only, then using the mysql query i get all the postcodes from database starting with E, problem is that i also get listing of postodes starting with EC, EN ... and i want postcodes sarting with E only.

Tried some options but i can't get to make it work..

Can you help me out here please ..

Thanks a lot in advance in advance.

Re: Get a specific list of postcodes with MySQL Like Operato

Posted: Fri May 03, 2013 9:08 am
by nita

Code: Select all


mysql_query("SELECT * FROM coverparked WHERE postcode regexp '^{$postcode1}[0-9]{1,}' ORDER BY postcode");

Solved

Re: Get a specific list of postcodes with MySQL Like Operato

Posted: Fri May 03, 2013 1:10 pm
by requinix
You can also replace all the digits with "[0-9]" and feed that to REGEXP.

And stop using ereg*() functions. They're slow, old, and have been deprecated for a long time now. Use the more powerful preg_*() functions instead.

Code: Select all

$postcodematch = preg_replace('/\d/', '[0-9]', $postcode);

"SELECT * FROM coverparked WHERE postcode REGEXP '^$postcodematch$'";