duandou8120 2013-06-10 13:06
浏览 48

使用html内容动态填充数组而不剥离标记

I have some HTML Content.

Eg.

<p>Ask a question</p><p>Wait for an answer</p><p>Vote up an Answer</p>

I want to use php to input each paragraph/div or any other html element separately as elements of an array

$arr[0]="<p>Ask a question</p>";
$arr[1]="<p>Wait for an answer</p>";

I want to do the above task dynamically.

  • 写回答

1条回答 默认 最新

  • duanlang0025 2013-06-10 13:13
    关注

    Lots of ways to do this. My first approach would be to use preg_match_all():

    Assume your html is in $html:

    preg_match_all( '|<p>.+?</p>|si', $html, $matches );

    $matches will then be an array-of-arrays of 1 element x N elements, where N is the number of matches.

    $matches[0][0] == '<p>Ask a question</p>';
    $matches[0][1] == '<p>Wait for an answer</p>';
    ...
    

    Edit: this can be generalized to match other tags, but a DOM parser should be used instead after the complexity requirements outweigh what regular expressions are capable of parsing.

    If you want to match a fixed set of non-nestable tags, this approach will work, but if the desired tags are nestable or self-closing, then regular expressions are not the way to go and using a simple DOM parser will be the right solution.

    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏