2015-01-17 53 views
0

我正在寻找一种方式来改造这个:更换HTML标记的HREF

...<a href="showinfo:3875//[integer]">[inner content]</a>... 

进入这个:

...<a href="http://somelink.com/[inner content]">[inner content]</a>... 

的情况下有多个链接与其他showinfo:整数]值。 (我可以处理这些的)

感谢您的帮助, 巴林特

编辑:多亏了凯撒的答案,这里是工作的代码片段:

$html = $a; 

$dom = new \DOMDocument; 
@$dom->loadHTML($html); //Cannot guarantee all-valid input 

foreach ($dom->getElementsByTagName('a') as $tag) { 
    // Fixed strstr order and added a != false check - the, because the string started with the substring 
    if ($tag->hasAttribute('href') && strstr($tag->getAttribute('href'), 'showinfo:3875') != false) { 
     $tag->setAttribute('href', "http://somelink.com/{$tag->textContent}"); 
     // Assign the Converted HTML, prevents failing when saving 
     $html = $tag; 
    } 
} 
return $dom->saveHTML($dom); 
} 

回答

1

可以使用DOMDocument一个相当可靠的以及处理DOM节点及其属性的快速方法等。提示:比(大多数)正则表达式快得多,也更可靠。现在,你有你的DOM准备

// Your original HTML 
$html = '<a href="showinfo:3875//[integer]">[inner content]</a>'; 

$dom = new \DOMDocument; 
$dom->loadHTML($html); 

,您可以使用该DOMDocument方法或DOMXPath通过它来搜索并获得您的目标元素。

实施例使用XPath:

$xpath = new DOMXpath($dom); 
// Alter the query to your needs 
$el = $xpath->query("/html/body/a[href='showinfo:']"); 

或例如通过ID与DOMDocument方法:

// Check what we got so we have something to compare 
var_dump('BEFORE', $html); 

foreach ($dom->getElementsByTagName('a') as $tag) 
{ 
    if (
     $tag->hasAttribute('href') 
     and stristr($tag->getAttribute('href'), 'showinfo:3875') 
     ) 
    { 
     $tag->setAttribute('href', "http://somelink.com/{$tag->textContent}"); 

     // Assign the Converted HTML, prevents failing when saving 
     $html = $tag; 
    } 
} 

// Now Save Our Converted HTML; 
$html = $dom->saveHTML($html); 

// Check if it worked: 
var_dump('AFTER', $html); 

就这么简单。

+0

谢谢 - 效果很好! – molbal

+0

编辑:在问题中添加最终解决方案 – molbal

+0

@molbal关于您编辑的问题的一些注释:您可能想使用'stristr()'(请参阅编辑答案)。你也不需要检查'!= false'。忽略它是一样的。但是,如果你这样做,至少用'!=='做一个类型安全检查。如果你**得到警告**,那么请按照[这个答案](http://stackoverflow.com/questions/1148928/disable-warnings-when-loading-non-well-formed-html-by-domdocument-php/17559716#17559716)查看如何禁止警告。或者只是_fix_你的HTML,如果你在控制它:) – kaiser