preg_match () Pattern

3 отговора 249 прегледа
#1

preg_match () Pattern

Трябва ми pattern за функцията preg_match() чрез който да "екстракт-вам" всички линкове от някой HTML source. Трабва ми само URL-то от целия таг <a href="url.com">

Все пак животът е прекрасен, като се вземе в предвид безплатната обиколка около Слънцето
Отговор
в отговор на Gemar #2

Re: preg_match () Pattern



<?php
$str="uhe[fhue[ufheufheufuefuefhufheuf<a href='test'>alabalanica</a>[fh[efe[fe]<a href='test'>nicaalabalanica</a>";
/**************************************************
След preg_match_all в масива $math
ще имаш "първата част" от
всички линкове от стринга. Би било
интересно някой да покаже как ще вземем
само URL-a в href атрибута - проблема е
че ако го вземем директно него - взимаме
и URL-a ако има JavaScript в стринга -
(window.location.href=fjifj.html) например ..
**************************************************/
$math=array();
$res=preg_match_all("#<a[^>]*>#",$str,$math);
var_dump($math);
?>



Отговор
в отговор на Учeщ #3

Re: Намерих код

Благодаря! Аз намерих цял код. Смятах на един ред да напиша паттерна, но се оказа по-сложно от колкото си мислех. В следващият код са го описали стъпка по стъпка:

<?php
$html="uhe[fhue[ufheufheufuefuefhufheuf<a href='test'>alabalanica</a>[fh[efe[fe]<A href='test'>nicaalabalanica</a>";

$href_regex ="<"; // 1 start of the tag
$href_regex .="\s*"; // 2 zero or more whitespace
$href_regex .="a"; // 3 the a of the tag itself
$href_regex .="\s+"; // 4 one or more whitespace
$href_regex .="[^>]*"; // 5 zero or more of any character that is _not_ the end of the tag
$href_regex .="href"; // 6 the href bit of the tag
$href_regex .="\s*"; // 7 zero or more whitespace
$href_regex .="="; // 8 the = of the tag
$href_regex .="\s*"; // 9 zero or more whitespace
$href_regex .="[\"']?"; // 10 none or one of " or '
$href_regex .="("; // 11 opening parenthesis, start of the bit we want to capture
$href_regex .="[^\"' >]+"; // 12 one or more of any character _except_ our closing characters
$href_regex .=")"; // 13 closing parenthesis, end of the bit we want to capture
$href_regex .="[\"' >]"; // 14 closing chartacters of the bit we want to capture

$regex = "/"; // regex start delimiter
$regex .= $href_regex; //
$regex .= "/"; // regex end delimiter
$regex .= "i"; // Pattern Modifier - makes regex case insensative
$regex .= "s"; // Pattern Modifier - makes a dot metacharater in the pattern
// match all characters, including newlines
$regex .= "U"; // Pattern Modifier - makes the regex ungready

//$html = "......";

//if preg_match was used here, it would only find the first match for the regular expression
if (preg_match_all($regex, $html, $links)) {

print("<P>Links: <pre>");
print_r($links[1]);
print("</pre></P>");
}

else {
print("No links.");
}

?>

Все пак животът е прекрасен, като се вземе в предвид безплатната обиколка около Слънцето
Отговор
в отговор на Gemar #4

Re: Намерих код

Ето и патерна на 1 ред: /<\s*a\s+[^>]*href\s*=\s*[\"']?([^\"' >]+)[\"' >]/isU

Като цяло може да се напише следната функция:

function extract_links ($html) {
$links = array ();
preg_match_all("/<\s*a\s+[^>]*href\s*=\s*[\"']?([^\"' >]+)[\"' >]/isU", $html, $links);
return $links[1];
}

Все пак животът е прекрасен, като се вземе в предвид безплатната обиколка около Слънцето

Редактирано от Gemar на

Отговор