【发布时间】:2011-06-11 20:16:35
【问题描述】:
我想将一些文本解析成一个数组:
我的文字是这样的:
You've come to the {right; correct; appropriate} place! Start by {searching; probing; inquiring} our site below, or {browse; {search; lookup; examine}} our list of popular support articles.
第三组词有嵌套标签。如何忽略打开和关闭嵌套标签以实现数组如
$tags[0][0] = 'right';
$tags[0][1] = 'suitable';
$tags[0][2] = 'appropriate';
$tags[1][0] = 'searching';
$tags[1][1] = 'probing';
$tags[1][2] = 'inquiring';
$tags[2][1] = 'browse';
$tags[2][2] = 'search';
$tags[2][3] = 'lookup';
$tags[2][4] = 'examine';
基本上忽略了标签的嵌套。 任何帮助将不胜感激。
我目前唯一的想法是逐个字符地遍历文本,直到找到一个 { 这会增加一个“深度”变量。捕获介于两者之间的单词,直到我找到一个 } 减小深度变量并在它返回零时停止捕获单词。我只是想知道是否有更简单的方法可以做到这一点。谢谢。
感谢您的出色帮助,我对其进行了一些修改以提出以下解决方案。
$code = "You've come to {the right; the correct; the appropriate} place!
Start by {searching; probing; inquiring} our site below, or
{browse; {search; {foo; bar}; lookup}; examine} our list of
popular support articles.";
echo $code."\r\n\r\n";
preg_match_all('/{((?:[^{}]*|(?R))*)}/', $code, $matches);
$arr = array();
$r = array('{','}');
foreach($matches[1] as $k1 => $m)
{
$ths = explode(';',str_replace($r,'',$m));
foreach($ths as $key => $val)
{
if($val!='')
$arr[$k1][$key] = trim($val);
$code = str_replace($matches[0][$k1],'[[rep'.$k1.']]',$code);
}
}
echo $code;
退货
你来到了{右边;正确的;合适的}地方!从{搜索开始;探测;在下面查询我们的网站,或{浏览; {搜索; {富;酒吧};抬头};检查}我们的热门支持文章列表。
你来到了 [[rep0]] 地方!从下面的 [[rep1]] 我们的网站或 [[rep2]] 我们的热门支持文章列表开始。
【问题讨论】:
-
删除任何嵌套的大括号也会有所帮助 - 在任何嵌套级别
标签: php parsing variables tags