将字符串分解为数组
可能很容易做到,但我似乎无法生成正确的正则表达式。
假设我有这个字符串
$string = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" /><h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p><h2>Header 3</h2><p>ajdas ahkds hakd</p>';
,并且我需要这样的
$array[0] = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" />';
$array[1] = '<h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p>';
$array[2] = '<h2>Header 3</h2><p>ajdas ahkds hakd</p>';
...等等,如果我的字符串包含更多这些 H2 块。
因此,分割点位于 H2,并且需要保留 HTML 标签。有什么指点吗?
Probably easy to do but I can't seem to generate the correct regex.
Say I have this string
$string = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" /><h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p><h2>Header 3</h2><p>ajdas ahkds hakd</p>';
And I need it like this
$array[0] = '<h2>Header 1</h2><p>ahs da sdka dshk asd haks</p><img src="http://dummyimage.com/100x100/" width="100" height="100" alt="Alt" />';
$array[1] = '<h2>Header 2</h2><p>asdkhas daksdha kd ahs</p><em>Lame</em><p>trhkbasd akhsd ka dkhas</p>';
$array[2] = '<h2>Header 3</h2><p>ajdas ahkds hakd</p>';
...and so on if my string contains more of those H2 blocks.
So, the split-point is at H2 and it needs to keep the HTML-tags. Any pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
preg_split()
与开始标记的正前瞻一起使用:正前瞻只是告诉正则表达式解析器拆分
周围的文本,但不会消除该标记。如果您按
/
/
拆分,标签就会消失,就像您使用explode()
拆分一样。Use
preg_split()
with a positive lookahead for the opening tag:The positive lookahead simply tells the regex parser to split text surrounding
<h2>
, but not eliminate the tag. If you split by/<h2>/
, the tag disappears, just like if you split withexplode()
.或者
or
不过,从 PHP 5.3.0 开始,这已被弃用。
This is deprecated as of PHP 5.3.0 though.