php
  • regex
  • dom
  • replace
  • 2017-06-02 2 views 0 likes 
    0
    $x = 'A fox was <a href="/xyz/dancingwith">Dancing with</a> light. The night <a href="/xyz/treeare">tree are</a> growing.'; 
    
    I want to become this 
    
    $x = 'A fox was <a href="/xyz/dancing-with">Dancing with</a> light. The night <a href="/xyz/tree-are">tree are</a> growing.'; 
    

    i allePHP ersetzen Urls mit Anchor Text

    <a href="xyz">x y z</a> to <a href="x-y-z">x y z</a> 
    

    oder

    <a href="xaybzc">xA yB zC</a> to <a href="xa-yb-zc">xA yB zC</a> 
    

    ich mich das

    Bitte werden wollen ersetzen wollen Hilfe.

    +0

    Können Sie uns zeigen, was Sie versucht haben, die nicht funktioniert haben? –

    Antwort

    1
    <?php 
    
    $x = 'A fox was <a href="/xyz/dancingwith">Dancing with</a> light. The night <a href="/xyz/treeare">tree are</a> growing.'; 
    
    $doc = new DOMDocument; 
    $doc->loadHTML($x); 
    $anchors = $doc->getElementsByTagName('a'); 
    $len = $anchors->length; 
    for($i = 0; $i < $len; $i++) { 
        $newPath = preg_replace('/\s+/', '-',strtolower($anchors->item($i)->nodeValue)); 
        $oldHref = $anchors->item($i)->getAttribute('href'); 
        $url = explode('/', $oldHref); 
        array_pop($url); 
        array_push($url, $newPath); 
        $newUrl = implode('/', $url); 
    
    
         $anchors->item($i)->setAttribute('href', $newUrl); 
    
    } 
    $newHTML = $doc->saveHTML(); 
    echo $newHTML; 
    
    +0

    Ich habe es bereits versucht, aber nicht erfolgreich. –

    +0

    @DavidCorp bitte versuche meine neue Antwort. –

    +0

    Großartig! Es funktioniert gut. –

    Verwandte Themen