简体   繁体   English

PHP用锚文本替换网址

[英]PHP replace urls with Anchor text

$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 want to replace all 我想取代所有

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

or 要么

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

I want to become this 我想成为这个

Please Help me. 请帮我。

<?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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM