Search code examples
phpexplode

how to take part of a string using explode()


i have sample data like this :

enter image description here

i want to get integer in the red box. i now i can using explode(). but I am confused to apply in my problem. how can i apply explode to my problem?

this my code :

$ikan=$_POST['ikan']; //example : Katombo,(30 basket)
$kata=explode("(", $ikan);

Solution

  • We use explode two times after we explode the first array.

    CODE

    $ikan= 'Katombo,(30 basket)';
    $kata= explode(" ", explode("(", $ikan)[1])[0];
    echo $kata;
    

    OUTPUT

    30
    

    UPDATED ANSWER If you want to loop it and use regex. you can use the ff:

    $ikan= array('Katombo,(30 basket)', 'Layang,(0 basket)', 'Loka-loka, (0 basket)', 'Tongkol, (0 basket)');
    $kata = array();
    foreach($ikan as $value){
         $kata[] = explode(" ", explode("(", $value)[1])[0];
    }
    

    Using preg_match_all and regex

    $ikan= array('Katombo,(30 basket)', 'Layang,(0 basket)', 'Loka-loka, (0 basket)', 'Tongkol, (0 basket)');
    $kata = array();
    foreach($ikan as $value){
        preg_match_all("/(\d+)/", $value,$num);
        $kata[] = $num[0][0];
    }