Jump to content

[SOLVED] extract numeric values from string


vinpkl

Recommended Posts

hi all

 

i have a string like "123 abc 45".

 

i am using the below code to extract numeric from string. The result i get  for numeric value is "12345".

 

How can i get the result as "123" and "45" as separate two keywords.

 

<?php 
$string = "123 abc 45"; 
$chars = ''; 
$nums = ''; 
for ($index=0;$index<strlen($string);$index++) { 
    if(isNumber($string[$index])) 
        $nums .= $string[$index]; 
    else     
        $chars .= $string[$index]; 
} 
echo "Chars: $chars<br>Nums: $nums"; 

function isNumber($c) { 
    return preg_match('/[0-9]/', $c); 
} 
?> 

 

vineet

Link to comment
Share on other sites

<?php 
$string = "123 abc 45"; 
$chars = ''; 
$nums = ''; 
for ($index=0; $index<strlen($string); $index++) { 
    if( ctype_digit($string[$index]) )
    {
        if ($str)  $nums .= ' ';
          $nums .= $string[$index];
          $str   = False;
     }else{
        if (!$str)  $chars.= ' ';
          $chars .= $string[$index];
          $str    = True;
    }
} 
echo "Chars: $chars<br >Nums: $nums"; 
?> 

Link to comment
Share on other sites

  • 6 years later...
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.