我有一个字符串
p, br, a[href,title], ul, li, em, strong
我想把它转换成数组。我尝试使用explode
,但它没有按预期工作:
$tags = explode(',', $tags);
以上代码输出:
array (
0 => 'p',
1 => ' br',
2 => ' a[href',
3 => 'title]',
4 => ' ul',
5 => ' li',
6 => ' em',
7 => ' strong'
)
我应该怎么做才能得到这样的结果:
array (
0 => 'p',
1 => ' br',
2 => ' a' => array('href', 'title'),
4 => ' ul',
5 => ' li',
6 => ' em',
7 => ' strong'
)
如果你确定CSV总是有模式逗号和空格,你仍然可以使用添加了空格的explode()
:
$tags = explode(', ', $tags);
第二种选择是在每个值上使用trim()
:
foreach ($tags as &$tag) {
$tag = trim($tag);
}
unset($tag);
如果您正在从文件中读取CSV,最好的解决方案是使用fgetcsv()
函数。
试试这个:
$ar = explode(", ", $s);
for ($i = 0; $i < count($ar); $i++) {
if (strpos($ar[$i], ",")) { //if is array formatted
$begin = strpos($ar[$i], "[");
$name = substr($ar[$i], 0, $begin);
$content = substr(substr($ar[$i], $begin + 1), 0, -1);
$newAr = explode(",", $content);
unset($ar[$i]);
$ar[$i][$name] = $newAr;
}
}
$ar = array_values($ar);
给定$s = "p, br, a[href,title], ul, li, em, strong";
,var_dump($ar)将导致:
array(7) {
[0]=>
string(1) "p"
[1]=>
string(2) "br"
[2]=>
string(2) "ul"
[3]=>
string(2) "li"
[4]=>
string(2) "em"
[5]=>
string(6) "strong"
[6]=>
array(1) {
["a"]=>
array(2) {
[0]=>
string(4) "href"
[1]=>
string(5) "title"
}
}
}
字符串实际上由三种RegEx模式组成:带params的标签(如a[href,title]
)、不带params且后面有逗号的标签(像br
)以及最后一个不带param的标签。
$patterns = [
'tagWithoutParams' => '/('w+)',/',
'lastTagWithoutParams' => '/'w+$/',
'tagWithParams' => '/'w+'['w+[,'w]*']/',
];
$matches = [
'tagWithoutParams' => [],
'lastTagWithoutParams' => [],
'tagWithParams' => [],
];
$string = 'p, br, a[href,title], img[src,style], ul, li, em, strong';
preg_match_all($patterns['tagWithoutParams'], $string, $matches['tagWithoutParams']);
preg_match_all($patterns['lastTagWithoutParams'], $string, $matches['lastTagWithoutParams']);
preg_match_all($patterns['tagWithParams'], $string, $matches['tagWithParams']);
$tags = array_merge(
$matches['tagWithoutParams'][1],
$matches['lastTagWithoutParams'][0],
$matches['tagWithParams'][0]
);
/*
Another variant:
$patterns = ['tagWithoutParams'] => '/'w+',/';
and then
array_walk($matches['tagWithoutParams'][0], function (&$value) {
$value = str_replace(',', '', $value);
});
and
$tags = array_merge(
$matches['tagWithoutParams'][0],
$matches['lastTagWithoutParams'][0],
$matches['tagWithParams'][0]
);
*/
foreach ($tags as $key => $tag) {
if (strpos($tag, '[')) {
$tagName = substr($tag, 0, strpos($tag, '['));
$paramsString = substr($tag, strpos($tag, '[') + 1, (strpos($tag, ']') - strpos($tag, '[') - 1));
$paramsArray = explode(',', $paramsString);
$tags[$key] = [$tagName => $paramsArray];
}
}
// test output
echo '<pre>';
print_r($tags);