0

I have a PHP string separated by characters like this :

$str = "var1,'Hello'|var2,'World'|";

I use explode function and split my string in array like this :

$sub_str = explode("|", $str);

and it returns:

$substr[0] = "var1,'hello'";
$substr[1] = "var2,'world'";

Is there any way to explode $substr in array with this condition: first part of $substr is array index and second part of $substr is variable?

example :

$new_substr = array();
$new_substr["var1"] = 'hello';
$new_substr["var2"] = 'world';

and when I called my $new_substr it return just result ?

example :

echo $new_substr["var1"];

and return : hello

Nick
  • 138,499
  • 22
  • 57
  • 95
S R R
  • 73
  • 8

4 Answers4

3

try this code:

$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$array = [];
foreach ($sub_str as $string) {
   $data = explode(',', $string);
   if(isset($data[0]) && !empty($data[0])){
     $array[$data[0]] = $data[1];
   }
}
Jaydip kharvad
  • 1,064
  • 7
  • 13
3

You can do this using preg_match_all to extract the keys and values, then using array_combine to put them together:

$str = "var1,'Hello'|var2,'World'|";
preg_match_all('/(?:^|\|)([^,]+),([^\|]+(?=\||$))/', $str, $matches);
$new_substr = array_combine($matches[1], $matches[2]);
print_r($new_substr);

Output:

Array (
  [var1] => 'Hello'
  [var2] => 'World' 
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
2

You can do it with explode(), str_replace() functions.

The Steps are simple:

1) Split the string into two segments with |, this will form an array with two elements.

2) Loop over the splitted array.

3) Replace single quotes as not required.

4) Replace the foreach current element with comma (,)

5) Now, we have keys and values separated.

6) Append it to an array.

7) Enjoy!!!

Code:

<?php
$string = "var1,'Hello'|var2,'World'|";
$finalArray = array();
$asArr = explode('|', $string );
$find = ["'",];
$replace = [''];
foreach( $asArr as $val ){
 $val = str_replace($find, $replace, $val);
  $tmp = explode( ',', $val );
  if (! empty($tmp[0]) && ! empty($tmp[1])) {
   $finalArray[ $tmp[0] ] = $tmp[1];
  }
}
echo '<pre>';print_r($finalArray);echo '</pre>';

Output:

Array
(
    [var1] => Hello
    [var2] => World
)

See it live:

Pupil
  • 23,834
  • 6
  • 44
  • 66
1

Try this code:

$str = "var1,'Hello'|var2,'World'|";
$sub_str = explode("|", $str);
$new_str = array();
foreach ( $sub_str as $row ) {
  $test_str = explode( ',', $row );
  if ( 2 == count( $test_str ) ) {
    $new_str[$test_str[0]] = str_replace("'", "", $test_str[1] );
  }
}
print $new_str['var1'] . ' ' . $new_str['var2'];

Just exploding your $sub_str with the comma in a loop and replacing single quote from the value to provide the expected result.

Sami Ahmed Siddiqui
  • 2,328
  • 1
  • 16
  • 29