tags:

views:

49

answers:

3

Hello,

I have a field that is in this format

5551112391^HUMAN^HUMAN-800-800^6-main^^

The "5551112391" before the ^ is the number. How would I grab only that and not any of that other data?

Would you do this with regex? Let me know!

Thanks.

+2  A: 

You can make use of explode:

$var = '5551112391^HUMAN^HUMAN-800-800^6-main^^';
$arr = explode('^',$var);
$num = $arr[0]; 

Using regex:

$var = '5551112391^HUMAN^HUMAN-800-800^6-main^^';
if(preg_match('/^(\d+)/',trim($var),$m)){
   $num = $m[1]; 
}
codaddict
Exactly what I was looking for..Thank you!
zx
How would I get "main" using this?
zx
A: 

You're doing it in completely wrong way.
You treat mysql database as a flat text file. But it is not.

  1. All these fields must be separated and stored in separate columns.
  2. To get only certain data from the table, you should not select all rows and then compare one by one but make database do it for you:

    SELECT * FROM table WHERE number=5551112391

Col. Shrapnel
That's not my choice. The number is stored in the userdata field along with all that other information, so I have to do it this way.
zx
That's not an excuse, @zx try to learn database use a bit. We all store user data in our tables. nothing bad in normalizing it as well
Col. Shrapnel
I didn't code that part, it's asterisk doing that. I'm just working with the data given to me :)
zx
+1  A: 

Regex overkill, nice...

What about simple cast to int? Will work perfectly OK if the number is in the beginning of data. And definitely faster than regexps...

$var = '5551112391^HUMAN^HUMAN-800-800^6-main^^';
$num = (int)$var;

http://www.php.net/manual/en/language.types.type-juggling.php

eyescream