简体   繁体   中英

With PHP preg_match_all, get value of href

I don'T really understabd how regular expressions works even after I read this tutorial http://www.webcheatsheet.com/php/regular_expressions.php

Here is what I need to find:

<link type="text/html" rel="alternate" href="http://link"/>

And it should return:

http://link

Here is what I tried:

$find = preg_match_all(
    '/<link type="text/html" rel="alternate" href=".*',
    $file,
    $patterns2
);

You can laught :)

Thanks in advance for your help and your time :)

Parsing (X)HTML with regex is almost certainly wrong . Use a dedicated XML parser. There are plenty available for php.

using simplexml

$html = '<link type="text/html" rel="alternate" href="http://link"/>';
$xml  = simplexml_load_string($html);
$attr = $xml->attributes();

using dom

$dom = new DOMDocument;
$dom->loadHTML($html);
$nodes = $dom->getElementsByTagName('link');
$attr  = $nodes->item(0)->getAttribute('href');

You have to cover the needed text-chunk in brackets like (.*) , that is what will be returned

This one is working for me

<?php
preg_match_all('/<link type="text\/html" rel="alternate" href="(.*)"\/>/','<link type="text/html" rel="alternate" href="http://link"/>',$patterns2);
print_r($patterns2);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM