【问题标题】:PHP replace urls with Anchor textPHP用锚文本替换url
【发布时间】:2017-11-03 08:11:08
【问题描述】:
$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.';

我要全部替换

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

我想变成这样

请帮帮我。

【问题讨论】:

  • 您能告诉我们您尝试过哪些不起作用的方法吗?

标签: php regex dom replace


【解决方案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;

【讨论】:

  • @DavidCorp 请尝试我的新答案。
  • @DavidCorp 这很好,你能投票给我的答案吗? :)
  • $len = $anchors-&gt;length; for($i = 0; $i &lt; $len; $i++) {: 改为使用 foreach 循环:foreach ($anchors as $anchor) {
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-06
  • 1970-01-01
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多