0

とにかくhtmlを抽出するためにpreg_machを使用します(DOMDocumentを使用しようとしましたが、新しい行に問題がありました)...それが私のコードです..

1.html

<body>


            <!-- icon and title -->
            <div class="smallfont">
                <img class="inlineimg" src="images/icons/icon1.gif" alt="" border="0" />
                <strong>qrtoobah 3nwan</strong>
            </div>
            <hr size="1" style="color:#CCCCCC; background-color:#CCCCCC" />
            <!-- / icon and title -->


        <div id="post_message_14142536">

            <font size="7"><font color="red">msaha 700</font></font><br />
<font size="7"><font color="red">shamali 20</font></font><br />
<font size="7"><font color="red"> 1700 almetr</font></font><br />
<font size="7"><font color="#ff0000">sooom bs</font></font><br />
<font size="7"><font color="#ff0000">albee3 qreeb</font></font>
        </div>
        <!-- message -->


</body>

抽出.php

<?php 
$html = file_get_contents("1.html");
$pattern = '/<([!]+)([^]+).*>([^]+)(message\ \-\-\>)/';
   preg_match($pattern, $html, $matches);
 print_r($matches);


?>

...の間に何かを取得したいの<!-- icon and title -->)blablabla(<!-- / message -->ですが、その配列を取得します:

Array ( [0] => [1] => ! [2] => -- [3] => message --> ) 
4

1 に答える 1

0

strpos最初のタグ位置を見つけるために使用します。次に、。で終了タグも見つけますstrpos。つまり、あなたがどこから何を探しているのかを知っていて、それらがユニークである場合..では、preg_*関数で何が重要なのでしょうか?

したがって、このようなものはうまくいくと思います(ステップバイステップのアクションで私のアイデアを理解するために、コードを可能な限り明確にします):

$tag_begin = "<!-- icon and title -->";
$tag_end   = "<!-- message -->";
$begin     = strpos($tag_begin,$text)+strlen($tag_begin);
$end       = strpos($tag_end,$text);
$result    = substr($begin,$end, $text);


<!-- (.*) -->また、開くと閉じるまでのすべての構造を見つけて保存したい場合は、まったく同じことを行うことができます<!-- / (.*) -->
uのみを変更する必要があります-最初にpreg_matchですべての開始構造名を検索します。例えば:

$result_cnt = preg_match_all('#<!-- [^/].*-->#', $text , $openings);

// Output for your example HTML is:
$openings = 
array (
  0 => 
  array (
    0 => '<!-- icon and title -->',
    1 => '<!-- message -->',
  ),
)

その後、$openingsの1ループを実行し、何よりも必要なコードを見つけます。「/」文字を適切な場所で閉じる開口部に追加するだけです。

于 2012-09-07T22:35:04.470 に答える