17 May
Extract numeric values from string
Many time we have a mixed sentence which contains string and numbers. If we want to separate string and numbers then we can do easily with php default ctype_digit  function. Here i am writing a simple function using ctype_digit to perform this action.
function getCharNumber($string,$whatNeed,$numSprator=' ',$stringSprator=' '){ $characters = ''; $numbers = ''; $str = false; for($count=0; $count<strlen($string); $count++){ if(ctype_digit($string[$count])){ if($str) $numbers .= $numSprator; $numbers .= $string[$count]; $str = false; }else{ if(!$str) $characters.= $stringSprator; $characters .= $string[$count]; $str = true; } } if($whatNeed=='char') return $characters; elseif($whatNeed=='num') return $numbers; else return "Oops something wrong!!"; }
Now check result of this function
//your string $string = "Your have 5 cart and each cart includes 89 items. You need 10 more itmes with 2 carts fro Rs. 550.89."; //$whatneed must be 'char' if string required and 'num' if digit required $result = getCharNumber($string,'num'); echo "your string is : '$string' <br>"; echo $result;
Result should be like as below
your string is : ‘Your have 5 cart and each cart includes 89 items. You need 10 more itmes with 2 carts fro Rs. 550.89.’
5 89 10 2 550 89
NOTE: Keep in mind it will return numeric string not an numbers like integer or float . You can see output of above example it will return 550 and 89 instead of 550.89. Means numeric string not an numeric type value.
I am a software engineer who specializes in Internet applications. I have worked with a wide variety of technologies and programming languages to open source LAMP environments. I have more than 6 years of object-oriented programming experience and am highly proficient in ActionScript, PHP, MYSQL, JavaScript, Jquery and a multitude of other technologies used in modern web applications.
Follow me
Latest posts by Rajeev Achra (see all)
- Jquery webcam plugin - June 19, 2016
- How To Add and Delete Users on a CentOSServer - June 5, 2016
- How To Set Up vsftpd on CentOS 6 - June 5, 2016