Home > Enterprise >  php function for rading out values from string
php function for rading out values from string

Time:05-04

i want to make a php loop that puts the values from a string in 2 different variables. I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.

CodePudding user response:

You can strip characters other than numbers and delimiters, and then do explode to get an array of values.

$string = '"23":"673",4:6';

$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
  $pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);

This gives you:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(2) "23"
    [1]=>
    string(3) "673"
  }
  [1]=>
  array(2) {
    [0]=>
    string(1) "4"
    [1]=>
    string(1) "6"
  }
}

CodePudding user response:

    <?php
    
    $string = '"23":"673",4:6';
    
    
    //Remove quotes from string
    $string = str_replace('"','',$string);
    
    //Split sring via comma (,)
    $splited_number_list = explode(',',$string);
    
    //Loop first list
    foreach($splited_number_list as $numbers){
        //Split numbers via colon
        $splited_numbers = explode(':',$numbers);
        
        //Numbers in to variable
        $number1 = $splited_numbers[0];
        $number2 = $splited_numbers[1];
        
        echo $number1." - ".$number2 . "<br>";
    }
?>
  •  Tags:  
  • php
  • Related