"/ contact/new"を<a href="/contact/new">Contact us</a>
から取得したいと思います。条件は、リンクに「連絡先」または「連絡先」のテキストがある場合にhref値を取得するようなものです。クラスはありません。シンプルなhtml domを使って特定のコンテンツとのリンクを得る方法
どうすればいいですか?
"/ contact/new"を<a href="/contact/new">Contact us</a>
から取得したいと思います。条件は、リンクに「連絡先」または「連絡先」のテキストがある場合にhref値を取得するようなものです。クラスはありません。シンプルなhtml domを使って特定のコンテンツとのリンクを得る方法
どうすればいいですか?
regex
とPHP
の使用:
jQuery
を使用して
$text = '<a href="/contact/new">Contact us</a>';
preg_match_all('(<a href="([^"]*)">[Contact us|Contact]*</a>)', $text, $matches);
foreach ($matches[1] as $href) {
// Do whatever you want with the href attribute
echo $href;
}
:
すべてa
の要素を選択し、そのhtml()
はあなたがリターンattr.("href")
$("a").each(function(index, element) {
if ($(elem).html() == "Contact" || $(elem).html() == "Contact us") {
// Do whatever you want with the href attribute
console.log($(elem).attr("href"));
}
});
を探しているテキストであるかどうかを確認
私はこのコードで解決しました。明らかにCerrotta
foreach($dom->find('a') as $element) { echo $element->plaintext . '<br>'; }
@Matiasからのアプローチを取得した後これは、SimpleXMLはとXPathを使用して達成することができます。
file_get_contents
を使用してSimpleXMLにページを読み込む方法を調整するか、ページを変数に読み込んで渡す必要があります。
私はつかんでいたサンプルでは、XPathの方法は、複数の結果が返された場合によってフィルタリングする必要があります。マッチの配列を返します
<?php
$html = '
<a href="/contact/new">Contact us</a>
';
//Replace with your loading logic here
$xml = simplexml_load_string($html);
//Perform the search
$search = $xml->xpath('//a[contains(text(), "Contact us") or contains(text(), "Contact")]');
//Check the results have at least one value
if(count($search) !== 0 && $search !== false)
{
//Get first item
$item = $search[0];
//Get item attributes
$attributes = $item->attributes();
//Output the HREF attribute (need an existence check here (isset))
echo $attributes['href'];
}
の下に働くモックアップを作成しました最初の1つはノードのhref属性を出力します。
検索では、文字列/文書内の位置に関係なくすべてa
タグが検索され、「連絡先」または「連絡先」のいずれかが含まれていることを確認します。
注: XPathでは大文字と小文字が区別されますが、それを区別しないようにする方法がありますが、自分でこれを実装するか、チェックする条件を追加する必要があります。
あなたはケース非感受性は、別のスタックの問題をチェックする必要がある場合は、それは前にカバーされています
そのjQueryの、右?あなたはPHPでそれを作ることができますか? – prokawsar
PHPは 'a'タグを文字列のように解析しますか? –
はい、すべての 'a'タグを解析します。 – prokawsar