php
  • regex
  • dom
  • replace
  • 2017-06-02 66 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.'; 
    

    我要全部更換PHP替代的URL的錨文本

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

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

    我想成爲這個

    請幫助我。

    +0

    你能告訴我們你試過的東西沒有用嗎? –

    回答

    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

    我已經嘗試過使用它,但沒有成功。 –

    +0

    @DavidCorp請嘗試我的新答案。 –

    +0

    太棒了!它工作正常。 –

    相關問題