Php 从带有preg_匹配的页面代码中查找链接

Php 从带有preg_匹配的页面代码中查找链接,php,url,hyperlink,preg-match,Php,Url,Hyperlink,Preg Match,我想使用preg_match更改此选项: <li class="fte_newsarchivelistleft" style="clear: both; padding-left:0px;"><a class="fte_standardlink fte_edit" href="news,2480143,3-kolejka-sezonu-2014-2015.html">3 kolejka sezonu 2014/2015&nbsp;&raquo;&r

我想使用preg_match更改此选项:

<li class="fte_newsarchivelistleft" style="clear: both; padding-left:0px;"><a class="fte_standardlink fte_edit" href="news,2480143,3-kolejka-sezonu-2014-2015.html">3 kolejka sezonu 2014/2015&nbsp;&raquo;&raquo;</a></li>
                      <li class="fte_newsarchivelistright" style="height: 25px;">komentarzy: <span class="fte_standardlink">[0]</span></li>
我怎么做?我正在尝试使用preg\u match,但是这个链接太复杂了…

使用preg\u match确实太复杂了。正如在这个网站上多次提到的:regex+HTML不能很好地混合。Regex不适合处理标记。但是,DOM解析器是:

$dom = new DOMDocument;//create parser
$dom->loadHTML($htmlString);
$xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath
$elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue
$hrefs = array();//all href values
foreach ($elemsWithHref as $node)
{
    $hrefs[] = $node->getAttributeNode('href')->value;//assign values
}
在此之后,只需处理$hrefs中的值,这将是一个字符串数组,每个字符串都是href属性的值

使用DOM解析器和XPath向您展示其功能的另一个示例:

要用href值替换节点,只需执行以下操作:

获取父节点 构造文本节点 调用DOMDocument::replaceChild 通过调用save来写入文件,或者调用saveHTML或saveXML来获取作为字符串的DOM 例如:

$dom = new DOMDocument;//create parser
$dom->loadHTML($htmlString);
$xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath
$elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue
foreach ($elemsWithHref as $node)
{
    $parent = $node->parentNode;
    $replace = new DOMText($node->getAttributeNode('href')->value);//create text node
    $parent->replaceChild($replace, $node);//replaces $node with $replace textNode
}
$newString = $dom->saveHTML();

@user3898993:如果您在处理标记时想到正则表达式,请记住:。。。这是一种传奇式的回答:
$dom = new DOMDocument;//create parser
$dom->loadHTML($htmlString);
$xpath = new DOMXPath($dom);//create XPath instance for dom, so we can query using xpath
$elemsWithHref = $xpath->query('//*[@href]');//get any node that has an href attribtue
foreach ($elemsWithHref as $node)
{
    $parent = $node->parentNode;
    $replace = new DOMText($node->getAttributeNode('href')->value);//create text node
    $parent->replaceChild($replace, $node);//replaces $node with $replace textNode
}
$newString = $dom->saveHTML();