1

我想在 PHP 中拆分/分解一个字符串。字符串如下所示:

<strong>Label</strong><p>Value</p>

有了这个结果:

array(
    '<strong>Label</strong>',
    '<p>Value</p>'
)

我怎样才能做到这一点?

4

5 回答 5

2

你可以这样做:

$string = "<strong>Label</strong><p>Value</p>";
$pos = strpos($string,'<p>');
$array = array();
$array[] = substr($string, 0,$pos);
$array[] = substr($string,$pos);

或使用 preg_match:

preg_match('%(.*g>)(.*)%',$string,$array);
//$array[1] = '<strong>Label</strong>'
//$array[2] = '<p>Value</p>'
于 2013-03-07T20:40:07.083 回答
1

这不是总是比preg函数快吗?

<?php
$str = "<strong>Label</strong><p>Value</p>";
$str = explode( "g><p", $str );
$str = implode( "g>~<p", $str);
$str = explode( "~", $str );

请注意:标签可能会嵌套,逻辑会变得困难。

于 2013-03-07T20:36:21.590 回答
0

如果不做一些有点骇人听闻的事情,你将无法通过爆炸来实现这一点:

$str = "<strong>Label</strong><p>Value</p>";
$strExp = explode("<p>", $str);
$strExp[1] = "<p>" . $strExp[1];

我建议改用正则表达式。

于 2013-03-07T20:34:35.220 回答
0

这不是拆分的工作方式。您需要将 preg_split 与 PREG_SPLIT_DELIM_CAPTURE 标志一起使用。

于 2013-03-07T20:35:24.517 回答
0

这应该可以解决问题;

$string = "<strong>Label</strong><p>Value</p>";
$array = explode("\t", str_replace("><", ">\t<", $string));
于 2013-03-07T20:46:35.470 回答