2011-09-20 79 views
0

我有一个'a'标签的文本。我必须添加一些新的标签和属性。正则表达式的链接

它看起来像这样:

'Some test <a href="site">here</a>. Yet <a href="site2">another</a> test.' 

现在我得:

'Some test <noindex><a rel="nofollow" href="site">here</a></noindex>.' 
'Yet <noindex><a rel="nofollow" href="site2">another</a></noindex> test.' 

任何快速的方法来做到这一点用PHP?谢谢。

+0

无法解析[X] HTML与正则表达式。但是你可以用正确的结构化标记替代PHP中的正则表达式。这是一个有效的问题。 –

回答

2

像这样将覆盖最真实世界的情况:

$text = 'Some test <a href="site">here</a>. Yet <a href="site2">another</a> test.'; 

$regex = '%(<a\s)(.*?</a>)%i'; 
$replacement = '<noindex>$1rel="nofollow" $2</noindex>'; 

preg_replace($regex, $replacement, $text); 
0
$string = preg_replace('~<a.*?href=(.*?)>(.*?)</a>~msi', '<noindex><a rel="nofollow" href=$1>$2</a></noindex>', $html); 
+0

如果'href'包含' Raynos

1

铭记HTML正则表达式解析是一个坏主意(你应该使用类似DOMDocument代替),这应该做的它:

$str = 'Some test <a href="site">here</a>. Yet <a href="site2">another</a> test.'; 
echo preg_replace('/<a(.+?)<\/a>/', '<noindex><a$1</a></noindex>', $str); 
// Some test <noindex><a href="site">here</a></noindex>. Yet <noindex><a href="site2">another</a></noindex> test. 
1

只是想给DOM文档(docs)版本,由于传统观念认为“不要对HTM使用正则表达式大号!”。那么,这是一个很好的说法,但那又怎么样?那么,在这里你去:

// create a new DOMDocument 
    $doc = new DOMDocument(); 

    // load the string into the DOM 
    $doc->loadHTML('Some test <a href="site">here</a>. Yet <a href="site2">another</a> test.'); 

    // since we are working with HTML fragments here, remove <!DOCTYPE 
    $doc->removeChild($doc->firstChild);    

    // likewise remove <html><body></body></html> 
    $doc->replaceChild($doc->firstChild->firstChild->firstChild, $doc->firstChild); 

    //Loop through each <a> tag in the dom and wrap it with <noindex> 
    foreach($doc->getElementsByTagName('a') as $link) { 
     $parent = $link->parentNode; 
     $ni = $doc->createElement('noindex'); 
     $ni->appendChild($link->cloneNode(true)); 
     $parent->replaceChild($ni, $link); 
    } 

    echo $doc->saveHTML(); 

看看这里:http://codepad.org/ANi93sBj