2

imageである投稿hrefの最初のタグの属性の値を取得しようとしています。 これは私がこれまでに持っているものです: <a>

$pattern = "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i";
$output = preg_match_all($pattern, $post->post_content, $matches);
$first_link = $matches[1][0];

ただし、これは機能しません

機能するタグのsrc値を取得するコードがあります<img>

$pattern = "/<img.+src=[\'"]([^\'"]+)[\'"].*>/i";
$output = preg_match_all($pattern, $post->post_content, $matches);
$first_img = $matches[1][0];

私は一般的に正規表現とphpの専門家ではないので、何が間違っているのかわかりません。

また、適切で整理された正規表現のガイドが見つからなかったので、そのガイドへのリンクも役立ちます。

4

3 に答える 3

3

これは正規表現で解決すべき問題ではありません。HTML を解析したい場合、必要なのは HTML パーサーであり、PHP には既に優れた機能を備えた HTML パーサーがあります。

$html = <<<HTML
<a href="http://somesillyexample.com/some/silly/path/to/a/file.jpeg">
HTML;

$dom = new DomDocument;
$dom->loadHTML($html); // load HTML from a string
$elements = $dom->getElementsByTagName('a'); // get all elements with an 'a' tag in the DOM
foreach ($elements as $node) {
    /* If the element has an href attribute let's get it */
    if ($node->hasAttribute('href')) {
        echo $node->getAttribute('href') . "\n";
    }
}
/*
will output:

http://somesillyexample.com/some/silly/path/to/a/file.jpeg
*/

詳細については、DOMDocumentのドキュメントを参照してください。

于 2012-12-08T17:09:21.023 に答える
2

これには DOM パーサーを使用する必要があります。サードパーティのライブラリを使用できる場合は、これをチェックしてください。それはあなたの仕事を信じられないほど簡単にします:

$html = new simple_html_dom();
$html->load($post->post_content);

$anchor = $html->find('a', 0);
$first_link = $anchor->href;

なんらかの理由でこのライブラリを使用できない場合でも、正規表現よりもPHP の組み込み DOM モジュールを使用することをお勧めします。

于 2012-12-08T17:06:37.083 に答える
1

正規表現に関する注意事項:

 "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i"
      ^ that's greedy, should be +?
      ^ that's any char, should be not-closing-tag character: [^>]

 "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i"
            ^^^^^^ for readability use ['\"]

 "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i"
                       ^ that's any char, you might wanted \.

 "/<a.+href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\").*>/i"
                    ^^ that's ungreedy (good!)       ^ see above (greedy any char)

ここに PHP がないため、今はテストできませんが、これらの問題を修正すれば、問題はすでに解決されている可能性があります。また、デフォルトの「貪欲」を切り替えるパターン修飾子 も確認してください。/U

ただし、この問題は何度も解決されているため、既存のソリューション (DOM パーサー) を使用する必要があります。たとえば、href で引用符を許可していません (これはおそらく href では問題ありませんが、後で引用符が有効な文字である別の html 属性を解析するために正規表現をコピーして貼り付けます)。

于 2012-12-08T17:15:51.080 に答える