1

I need one help.i need to separate numeric value from character using PHP.I am explaining my code below.

 $subcatid=a1,a2,4,5

here i have some value with comma separator i need here separate numeric value(i.e-4,5) first and push them into a array then i have to separate rest numeric value from character(i.e-1 from a1,2 from a2) and push those separated value into another array.Please help me.

satya
  • 3,508
  • 11
  • 50
  • 130

4 Answers4

2

Try this

<?php
    $subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
$onlynum_subcatid = array_filter($subcatid_arr, 'is_numeric');
$onlynum = implode(",",$onlynum_subcatid );
echo "Only Number : ".$onlynum;
$notnum_subcatid = array_diff($subcatid_arr,$onlynum_subcatid );
$notnum = implode(",",$notnum_subcatid );
echo "\nNot Number : ".$notnum;
?>

Output is :

Only Number : 4,5
Not Number : a1,a2

check here : https://eval.in/539059

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
  • its only fetching the numeric value but i also separate the values those are with character and push them into another array. – satya Mar 19 '16 at 05:13
  • To get numbers from string with PHP : http://stackoverflow.com/questions/11243447/get-numbers-from-string-with-php – Niklesh Raut Mar 19 '16 at 06:44
0

Use this code

$subcatid="a1,a2,4,5";
$strArray = explode(',',$subcatid);
$intArr = array();

foreach($strArray as $key=>$value):

 if(preg_match('/^[0-9]*$/',$value)):
  $intArr[]=$value;
 else:

  $str2Arr = str_split($value);

  foreach($str2Arr as $keyStr=>$lett):

   if(preg_match('/^[0-9]*$/',$lett)):
    $intArr[]=$lett;
   endif;

  endforeach;
 endif;

endforeach;

var_dump($intArr);
0

in this code you can expect your result. Do process with the $number, $char array as required

<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
for($i=0;$i<sizeof($subcatid_arr);$i++){
    if(is_numeric($subcatid_arr[$i])){
    $number[]=$subcatid_arr[$i];
}
else{
    $char[]=$subcatid_arr[$i];
}
}
print_r($number);// 4,5
print_r($char);// a1,a2
?>
Vigneswaran S
  • 2,039
  • 1
  • 20
  • 32
0

If I am understanding correctly, you want to put all of the original numeric values into a single array and then filter just the numeric parts of the leftovers and put them in to a second array.

If this is correct then I believe this should do what you want.

<?php

$subcatid = 'a1,a2,4,5';
$subcat_array = explode(",",$subcatid);
$subNums1 = [];
$subNums2 = [];

foreach($subcat_array as $item) {
    if(is_numeric($item)) {
        // This pushes all numeric values to the first array
        $subNums1[] = $item;
    } else {
        // This strips out everything except the numbers then pushes to the second array
        $subNums2[] = preg_replace("/[^0-9]/","",$item);
    }
}

print_r($subNums1);
print_r($subNums2);

?>

This will return:

Array (
    [0] => 4
    [1] => 5 
)

Array (
    [0] => 1
    [1] => 2 
)
Ghostrogue
  • 36
  • 5