如何解析此字符串
name:john;phone:12345;website:www.23.com;
成为这样的
$name = "john";
$phone = "12345"
.....
因为我想将参数保存在一个表格列中,所以我看到使用此方法保存菜单/文章参数的joomla。
答案 0 :(得分:3)
像这样(爆炸()就是这样的方式):
$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
或variable
不能包含;
或:
答案 1 :(得分:1)
我是这样做的:
explode()
并将字符串拆分为;
作为分隔符。:
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];
答案 2 :(得分:0)
爆炸 - 按字符串分割字符串
<强>描述强>
返回一个字符串数组,每个字符串都是字符串的子字符串,通过在字符串分隔符形成的边界上将其拆分而形成。
<?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) ""
}
答案 3 :(得分: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>";
}
}
?>