Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP String Contains Integer

Tags:

php

mysql

I've the following strings as follows :

1BG200,1M400,1BA1000

And I want to to compare the above strings into Desc Order...

Code:

$sql = "SELECT * FROM collected WHERE c_no BETWEEN '".$from."' AND '".$to."' ORDER BY c_no Desc";

Output :

1M400
1BG200
1BA1000 

It should be 1000 is larger, then 400, 200..How can i compare them ? I believe its not right to compare string that contains integer ! And I can't find a correct solution for my issue ?

Some people suggested using preg_match or substr..But as you can see there are single and double characters ex ( M and BG ).

Sorry, I'm not that familiar with PHP.. Please Help !

like image 966
Alihamra Avatar asked Jun 24 '13 12:06

Alihamra


2 Answers

You can use a custom sort, looking only at the numerical part

function cmp($a, $b)
{
    $numa = intval(preg_replace('/[0-9]*[A-Z]+/', '', $a));
    $numb = intval(preg_replace('/[0-9]*[A-Z]+/', '', $b));
    if($a == $b) return 0;
    return ($a < $b) ? -1 : 1;
}

//Now get the list and sort
usort($list, "cmp");
like image 61
Otto Avatar answered Sep 30 '22 16:09

Otto


You can use preg_replace('/[0-9][A-Z]+/', '', $var) to remove first number and more then one letter after, and then use php usort.

like image 40
jcubic Avatar answered Sep 30 '22 16:09

jcubic