satya
satya

Reputation: 3560

How to seprate numeric value from charcter using PHP

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.

Upvotes: 1

Views: 73

Answers (4)

Ghostrogue
Ghostrogue

Reputation: 36

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 
)

Upvotes: 0

Niklesh Raut
Niklesh Raut

Reputation: 34914

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

Upvotes: 2

Vigneswaran S
Vigneswaran S

Reputation: 2094

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

Upvotes: 0

Misyaath Mohammed
Misyaath Mohammed

Reputation: 7

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

Upvotes: 0

Related Questions