With PHP preg_match_all, get value of href

独自空忆成欢 提交于 2019-11-30 16:08:12

问题


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 :)


回答1:


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');



回答2:


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




回答3:


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);
?>


来源:https://stackoverflow.com/questions/4587304/with-php-preg-match-all-get-value-of-href

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!