php preg_replace: find links and add a #hash to it?

◇◆丶佛笑我妖孽 提交于 2020-01-06 13:05:10

问题


i have the following structure...

$output = '<li><a href="http://forum.example.org">Something</a></li>' Actually $output holds multiple list-items.

What's the best and easiest way to apply a #hash to each links href? as in...

<li><a href="http://forum.example.org#something">Something</a></li>

Any idea how to solve that?

edit: btw it should always be the same #hash not as you might think in this example above, the #something is equal to the name of the link. So it should be #something for each link.

add_filter('wp_list_pages', 'add_hash'); /*Add #hash to wp_list_pages() function*/
function add_hash($output) {

        $dom = new DOMDocument();
        $dom->loadHTML($output);

        $a_tags = $dom->getElementsByTagName('a');

        foreach($a_tags as $a)
        {
            $value = $a->getAttribute('href');
            $a->setAttribute('href', $value . '#b');
        }

        $dom->saveHTML();

        return $output;
}

回答1:


$dom = new DOMDocument();
$dom->loadHTML($str); // Change to input variable

$a_tags = $dom->getElementsByTagName('a');

foreach($a_tags as $a)
{
    $value = $a->getAttribute('href');
    $a->setAttribute('href', $value . '#something');
}

// Get the new document with: $dom->saveHTML()

Edit:

In your above code, you need to change:

        $dom->saveHTML();

        return $output;
}

To:

        return $dom->saveHTML();
}


来源:https://stackoverflow.com/questions/5317503/php-preg-replace-find-links-and-add-a-hash-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!