[PHP] 指定したHTMLタグに挟まれたデータを列挙

2006年12月09日 土曜日 17時12分
E-Mail This Post/Page Print This Post/Page

指定したHTMLタグとその間に挟まれた文字列をマッチさせる方法を紹介します。これを応用して、選択したタグ内にある文字列をリストアップさせたり、必要ないタグに囲まれた文字列を消去させることができます。

使用する正規表現: #<$tagname>?(.*?)</$tagname\s*\/?>#s

これを使用して、HTMLデータが入っている変数 $data から <a> タグに囲まれた文字列を列挙させて見ます。

PHP:
  1. $data <<<HERE
  2. <a href="http://dowonders.net/pz/">top</a>
  3. <a href="http://dowonders.net/pz/wordpress">wordpress</a>
  4. <a href="http://dowonders.net/pz/php">php</a>
  5. HERE;
  6. $tagname = 'a'; //タグの名前を指定
  7. $tags= "#<$tagname>?(.*?)</$tagname\s*\/?>#s";
  8. preg_match_all($tags, $data, $mats);
  9. print_r($mats);

結果は以下のようになります。

Array
(
[0] => top
[1] => wordpress
[2] => php
)

では次に、必要ないタグ要素とそれに囲まれた文字列を消去してみます。php の デフォルトの関数、strip_tags() で HTML タグを一発で消去することができますが、strip_tags() では指定したタグのみを残すことができても、指定した以外を残すこと、またその間にある文字列を消すことはできません。

二番目と三番目の行に<li> タグを足しました。これで <li> タグとその間の文字列を消去してみます。

PHP:
  1. $data <<<HERE
  2. <a href="http://dowonders.net/pz/">top</a>
  3. <li><a href="http://dowonders.net/pz/wordpress">wordpress</a></li>
  4. <li><a href="http://dowonders.net/pz/php">php</a></li>
  5. HERE;
  6. $tagname = 'li'; //タグの名前を指定
  7. $tags= "#<$tagname>?(.*?)</$tagname\s*\/?>#s";
  8. preg_replace($tags, '', $data);
  9. echo $data;

以下、出力結果

top

この記事に関連するトピック

このエントリーへの Yahoogle Suggestions

Trackback this Post | Feed on comments to this Post

 

記事ヒット TOP 10

IT 関連 NEWS

    There is no entries available for this category.

PHP関連 NEWS

    There is no entries available for this category.

PHP Tips from Social Bookmarks

    There is no entries available for this category.

PHPに関するフォーラムトピック

    There is no entries available for this category.

Tag Cloud

admin Admin Drop Menus Admin Memo Admin Panel advanced drop menus array unique blog cron dabeya Dagon Design Sitemap Generator dropcap Edit N Place error Feedburner game google hack html HTML CSS Internet NEWS Permalink Redirect PHP phpBB2 plugin RSS scripts search stattraq template the content Ultimate Tag Warrior Web Management Windows XP Wordpress WP Plugins WPページ  拡張子 カスタマイズ カスタム関数 カテゴリー コード セキュリティ タグ トップページ トラックバック フィード 投稿 抜粋 日本語 時刻 時間 正規表現 表示 記事

サイト メニュー

Blogtimes image
ぱそずき :D)‐く © 2008
Close
E-mail It