所以我有很多大文本段落要解析。最终目标是将段落分隔成更小的帖子,这样我就可以将它们插入mysql中。
下面是一个字符串中某个段落的简短示例:
<?php
$longstring = '
(<b>John Smith</b>) at <b class="datetimeGMT">2011-01-10 22:13:01 GMT</b><hr>
Lots of text entered here under the first line.<br>And most of it is html, since it is for displaying in a web browser.<br></br></br>
(<b>Alan Slappy</b>) at <b class="datetimeGMT">2011-01-11 13:12:00 GMT</b><hr>
Forgot to put one more thing in the notes.........<br>blah blah blah
(<b>Joe Mama</b>) at <b class="datetimeGMT">2011-01-13 10:15:00 GMT</b><hr>
Groceries list:<br>Watermelons<br>Floss<br><br>email doctor
';
?>
是的,我有一个奇怪的项目,为每个条目解析这些字符串。是的,我同意任何人的看法,这不是一项很酷的任务。原始开发人员允许将文本附加到原始文本。对于某些场合来说,这不是一个坏主意,但对我来说确实如此。
我确实需要帮助,如何RegEx这个野兽,并将它放在前臂环中,这样我就可以开始清理它了。
以下是我的进展:
<?php
if(preg_match_all('/'(<b>.*?<hr>/', $longstring, $matches)){
print_r($matches);
}
/* output:
Array
(
[0] => Array
(
[0] => (<b>John Smith</b>) at <b class="datetimeGMT">2011-01-10 22:13:01 GMT</b><hr>
[1] => (<b>Alan Slappy</b>) at <b class="datetimeGMT">2011-01-11 13:12:00 GMT</b><hr>
[2] => (<b>Joe Mama</b>) at <b class="datetimeGMT">2011-01-13 10:15:00 GMT</b><hr>
)
)
*/
?>
所以,实际上,我在循环浏览每个条目的顶部方面做得很好。我有点自豪我发现了这一点。(正则表达式是我的克星)
所以现在我一直在想如何在每次迭代下面包含实际的文本。
有人知道我如何调整preg_match_all
以考虑每个"标题"下面的文本吗?
尝试使用preg_split:
$matches = preg_split("/'s*('(<b>.*?<hr>)'s*/s", trim($longstring), null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
print_r($matches);
注意:修剪应用于字符串以剪切前导空格和尾随空格。
结果将类似
Array
(
[0] => (<b>John Smith</b>) at <b class="datetimeGMT">2011-01-10 22:13:01 GMT</b><hr>
[1] => Lots of text entered here under the first line.<br>And most of it is html, since it is for displaying in a web browser.<br></br></br>
[2] => (<b>Alan Slappy</b>) at <b class="datetimeGMT">2011-01-11 13:12:00 GMT</b><hr>
[3] => Forgot to put one more thing in the notes.........<br>blah blah blah
[4] => (<b>Joe Mama</b>) at <b class="datetimeGMT">2011-01-13 10:15:00 GMT</b><hr>
[5] => Groceries list:<br>Watermelons<br>Floss<br><br>email doctor
)
试试这个
if(preg_match_all('/'(<b>(?:(?!'(<b>).)*/s', $longstring, $matches)){
print_r($matches);
}
如果您解析HTML而不是仅仅尝试正则表达式,这将更容易,除非您可以保证HTML的格式。
您可能想看看健壮和成熟的PHP HTML解析器。