2011-09-20 7 views
0

J'ai un texte avec des balises 'a'. Je dois ajouter de nouveaux tags et attributs.regex pour un lien

Il ressemble à ceci:

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

Maintenant, je dois obtenir:

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

Les moyens rapides pour le faire avec php? Merci.

+0

Vous ne pouvez pas analyser [X] HTML avec regex. Mais vous pouvez remplacer l'expression régulière en PHP par un balisage bien structuré. C'est une question valide. –

Répondre

2

Quelque chose comme cela couvrirait la plupart des cas réels du monde:

$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

Que faire si 'href' contient' Raynos

1

Compte tenu du fait que le HTML analyse avec l'expression régulière est une mauvaise idée (vous devez utiliser quelque chose comme DOMDocument à la place), cela devrait faire il:

$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

Je voulais juste donner la version DOMDocument (docs), étant donné que la sagesse conventionnelle dit: « ne pas utiliser RegEx sur HTM L !! ". Eh bien, c'est une bonne chose à dire, mais alors quoi? Eh bien, ici vous allez:

// 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(); 

Check it out ici: http://codepad.org/ANi93sBj