jamina1 Posted September 26, 2007 Share Posted September 26, 2007 I've tried all I can, but I can't get PHP to convert a string to an integer (or pull the numbers OUT of a string) if it doesn't start with a number, which is an issue. Basically, i'm trying to pull the integers only out of various model numbers for pieces of equipment our store is selling - examples would be something like S820D or MS1798. I only need the 820 or the 1798 from these strings, but PHP doesn't want to play nice with either: $product_model = "S820D"; $var = intval($product_model); or $var = (int) $product_model; Help! Quote Link to comment https://forums.phpfreaks.com/topic/70798-convert-string-to-integer-not-starting-with-a-number/ Share on other sites More sharing options...
GingerRobot Posted September 26, 2007 Share Posted September 26, 2007 The only way i can think is to go through character by character, and create a new string with only the numeric characters: <?php $product_model = "S820D"; $num = ''; for($x=0;$x<strlen($product_model);$x++){ if(is_numeric($product_model[$x])){ $num.=$product_model[$x]; } } echo $num; ?> Quote Link to comment https://forums.phpfreaks.com/topic/70798-convert-string-to-integer-not-starting-with-a-number/#findComment-355979 Share on other sites More sharing options...
Wuhtzu Posted September 26, 2007 Share Posted September 26, 2007 Another option is regex: <?php $product_model = "s820d"; preg_match('/[0-9]+/', $product_model, $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?> Quote Link to comment https://forums.phpfreaks.com/topic/70798-convert-string-to-integer-not-starting-with-a-number/#findComment-355981 Share on other sites More sharing options...
corbin Posted September 26, 2007 Share Posted September 26, 2007 Another way to do it with regexp could be: $string = 'ab23fg43ff3r'; $numbers = preg_replace('/[^0-9]/', '', $string); echo $numbers; //23433 Quote Link to comment https://forums.phpfreaks.com/topic/70798-convert-string-to-integer-not-starting-with-a-number/#findComment-355989 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.