简体   繁体   English

使用 PHP 转换 HTML 以显示链接 URL

[英]Converting HTML to show link URLs using PHP

Is it possible to convert the first block a text to the second block of text using PHP?是否可以使用 PHP 将第一个文本块转换为第二个文本块? If so, how?如果是这样,如何? Thanks谢谢

<div>
 <p>Some text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
 <p>More text & a <a href="http://abc.com/index.php?x=123&y=abc">link</a>. Done</p>
</div>


<div>
 <p>Some text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
 <p>More text & a <strong>link</strong> <i>(http://abc.com/index.php?x=123&y=abc)</i>. Done</p>
</div>

EDIT.编辑。 Per Andy's recommendation, looking at something like the following.根据安迪的建议,查看如下内容。 Still struggling on the converting of links, but it looks like a good start.仍在努力转换链接,但它看起来是一个好的开始。

libxml_use_internal_errors(true);   //Temporarily disable errors resulting from improperly formed HTML
$doc = new DOMDocument();
$doc->loadHTML($array['message_text']);
$a = $doc->getElementsByTagName('a');
foreach ($a as $link)
{
    //Where do I go from here?
}
$array['message_text'] = $doc->saveHTML();
libxml_use_internal_errors(false);

First off, your HTML is malformed, as & needs to be encoded as its HTML entity &amp;首先,您的 HTML 格式不正确,因为&需要编码为其 HTML 实体&amp; . . Fixing this gives us:解决这个问题给了我们:

$html = '<div>
 <p>Some text &amp; a <a href="http://abc.com/index.php?x=123&amp;y=abc">link</a>. Done</p>
 <p>More text &amp; a <a href="http://abc.com/index.php?x=123&amp;y=abc">link</a>. Done</p>
</div>';

From here, you shouldn't use a regex.从这里开始,您不应该使用正则表达式。 It is incredibly brittle and not meant for parsing HTML.它非常脆弱,不适合解析 HTML。 Instead, you can use PHP's DOMDocument class to parse the HTML, extract the <a> tags, pull the information you want from them, create the new HTML elements, and insert them into the appropriate place.相反,您可以使用 PHP 的DOMDocument类来解析 HTML,提取<a>标签,从中提取您想要的信息,创建新的 HTML 元素,并将它们插入到适当的位置。

$doc = new DOMDocument;
$doc->loadHTML( $html);

$xpath = new DOMXPath($doc);
foreach( $xpath->query( '//a') as $a) {
    $strong = $doc->createElement( 'strong', $a->textContent);
    $i = $doc->createElement( 'i', htmlentities( $a->getAttribute('href')));
    $a->parentNode->insertBefore( $strong, $a);
    $a->parentNode->insertBefore( $i, $a);
    $a->parentNode->removeChild( $a);
}

This prints :打印

<p>Some text &amp; a <strong>link</strong><i>http://abc.com/index.php?x=123&amp;y=abc</i>. Done</p> 
<p>More text &amp; a <strong>link</strong><i>http://abc.com/index.php?x=123&amp;y=abc</i>. Done</p>

You will need to use Regular Expressions.您将需要使用正则表达式。

$newHtml = preg_replace(/<a[\s\w"'=\t\n]*href="(.*?)"[\s\w"'=\t\n]*>(.*?)<\/a>/i, "<strong>${2}</strong> <i>${1}</i>", $html);

You can see the regex here你可以在这里看到正则表达式

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

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