Jump to content

Convert string to integer - not starting with a number


jamina1

Recommended Posts

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!

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;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.