我怎样才能解析这个字符串
name:john;phone:12345;website:www.23.com;
变成这样
$name = "john";
$phone = "12345"
.....
因为我想将参数保存在一个表格列中,所以我看到 joomla 使用这种方法来保存菜单/文章参数。
像这样的东西(explode()就是这样):
$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;
请注意:字符串必须是这样variable_name:value;variable_name2:value
的,并且variable_name
orvariable
不能包含;
or:
这是我的做法:
explode()
并拆分字符串 with;
作为分隔符。explode()
通过:
implode()
代码:
$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;
}
}
输出:
Array
(
[0] => john
[1] => 12345
[2] => www.23.com
)
现在,要将这些值放入变量中,您可以简单地执行以下操作:
$name = $result[0];
$phone = $result[1];
$website = $result[2];
explode —逐个字符串拆分
描述
返回一个字符串数组,每个字符串都是通过在字符串分隔符形成的边界上拆分字符串而形成的子字符串。
<?php
$string = "name:john;phone:12345;website:www.23.com;";
$pieces = explode(";", $string);
var_dump($pieces);
?>
输出
array(4) {
[0]=>
string(9) "name:john"
[1]=>
string(11) "phone:12345"
[2]=>
string(18) "website:www.23.com"
[3]=>
string(0) ""
}
尝试这个
<?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>";
}
}
?>