简体   繁体   English

用链接文本/名称替换 href

[英]Replace href with link text/name

I have a string in php with many a tags... See below for more clerification我在 php 中有一个带有许多标签的字符串...有关更多说明,请参见下文

It is like.... bla bla bla bla bla bla就像.... bla bla bla bla bla bla

<a href="test.php">link1</a'> hellllo

<a href="test.php">link2</a> hiiiiiiiiii

My problem is I want to replace href ie test.php with link1,link2,link3.... so on.我的问题是我想用link1、link2、link3....替换href,即test.php。

Kindly help.请帮忙。 ' ' are added for show only consider them as proper links ' ' 被添加为仅显示将它们视为正确的链接

use DOMDocument and friends: http://php.net/manual/en/class.domdocument.php使用 DOMDocument 和朋友: http://php.net/manual/en/class.domdocument.php

Something like this, but unsure as it is untested, and I am only going off documentation.像这样的东西,但不确定,因为它未经测试,我只是离开文档。

$xml = new DOMDocument();
$xml->loadHTML($input_string);
$link_list = $xml->getElementsByTagName('a');
$link_list_length = $link_list->length;
for ($i = 0; $i < $link_list_length; $i++) {
    $attributes = $link_list->item($i)->attributes;
    $href = $attributes->getNamedItem('href');
    $href->value = $link_list->item($i)->nodeValue;
}
$output_string = $xml->saveHTML();

First off, do not use regular expressions.首先,不要使用正则表达式。 It might work for a bit, but down that path lies madness.它可能会起作用一点,但在那条路上是疯狂的。

What you want to do is parse the string into XML using PHP's "DOM" library.您要做的是使用 PHP 的“DOM”库将字符串解析为 XML。 This converts the HTML (assuming it is valid HTML and not malformed) into a set of objects that you can navigate, modify, and then convert back into a string later.这会将 HTML(假设它是有效的 HTML 并且没有格式错误)转换为一组对象,您可以导航、修改这些对象,然后稍后再转换回字符串。

You can find several guides on the web, like this one .您可以在 web 上找到几个指南,例如这个

This is purely off-the-cuff code, I have not tested it, but it should give you a general idea:这纯粹是现成的代码,我没有测试过,但它应该给你一个大致的想法:

$doc = new DOMDocument();
$doc->loadHtml($YOUR_DATA); 
$links = $doc->getElementsByTagName( "a" );
foreach( $links as $link )
{
    // Modify $link however you need to
}
$CONVERTED_DATA = $doc->saveHtml();

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

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