Jump to content

Convert string to integer - not starting with a number


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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.