user2801717
user2801717

Reputation: 13

Parsing a string separated by semicolon

How can I parse this string

name:john;phone:12345;website:www.23.com;

into becoming like this

$name = "john";
$phone = "12345"
.....

because I want to save the parameter in one table column, I see joomla using this method to save the menu/article parameter.

Upvotes: 0

Views: 3186

Answers (4)

JTC
JTC

Reputation: 3464

Something like this(explode() is the way):

$string = 'name:john;phone:12345;website:www.23.com';

$array = explode(';',$string);

foreach($array as $a){
  if(!empty($a)){
   $variables = explode(':',$a);
   $$variables[0] = $variables[1];
  }
}

echo $name;

Working example

Please note: String must be like this, variable_name:value;variable_name2:value and the variable_name or variable cant contain ; or :

Upvotes: 3

Amal Murali
Amal Murali

Reputation: 76666

Here's how I'd do it:

  • Use explode() and split the string with ; as the delimiter.
  • Loop through the result array and explode() by :
  • Store the second part in a variable and push it into the result array
  • Optionally, if you want to convert the result array back into a string, you can use implode()

Code:

$str = 'name:john;phone:12345;website:www.23.com;';
$parts = explode(';', $str);
foreach ($parts as $part) {
    if(isset($part) && $part != '') {
        list($item, $value) = explode(':', $part);
        $result[] = $value;
    }
}

Output:

Array
(
    [0] => john
    [1] => 12345
    [2] => www.23.com
)

Now, to get these values into variables, you can simply do:

$name = $result[0];
$phone = $result[1];
$website = $result[2];

Demo!

Upvotes: 1

Janak Prajapati
Janak Prajapati

Reputation: 886

try this

<?php

$str = "name:john;phone:12345;website:www.23.com";

$array=explode(";",$str);

if(count($array)!=0)
{
foreach($array as $value)
{

    $data=explode(":",$value);

    echo $data[0]." = ".$data[1];
    echo "<br>";
}
}
?>

Upvotes: 0

underscore
underscore

Reputation: 6877

Use explode()

explode — Split a string by string

Description

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.

  <?php

    $string = "name:john;phone:12345;website:www.23.com;";

    $pieces = explode(";", $string);

    var_dump($pieces);

?>

Output

array(4) {
  [0]=>
  string(9) "name:john"
  [1]=>
  string(11) "phone:12345"
  [2]=>
  string(18) "website:www.23.com"
  [3]=>
  string(0) ""
}

DEMO

Upvotes: 0

Related Questions