从内容中提取链接

时间:2018-10-01 15:58:58

标签: php regex hyperlink attributes wysiwyg

我正在寻找一种解决方案,仅在单个页面上显示字符串(我的所见即所得内容)中的链接。

首先提取我的所有链接,然后用链接标题属性替换每个链接内容。

这是我的内容的示例:

<p>Iriaequam igit adhuidie eo, condam ciorteli pripsenit Catu quam nos, sediess ilint. Scipios alabi 
    <a title="link title 1" href="http://www.google.com" target="_blank" rel="1 noopener">incepopori</a> 
    senatifec iam pra re hoc, caet? Bus viritid 
    <a title="Link title 2" href="http://www.facebook.com" target="_blank" rel="2 noopener">epectam</a> 
    etorum imus revilla dit fore tem. Quam fugitas sitius coribusciam, voluptam alique velibus ut dit earum simodia quo conseque vit, cusa core pro odictur aut hilitatquat et atur amet et veliquatur. Ici aceruptae es.
</p>

这就是我要在页面上显示的内容:

<a href="http://www.google.com" target="_blank" rel="1">link title 1</a>
<a href="http://www.facebook.com" target="_blank" rel="2">link title 2</a>

这是我到目前为止所尝试的:

<?php 

$post_content = get_the_content();

preg_match_all('/href="(.*?)"/s', $post_content, $matches);

$count = count($matches[1]);

for ($row = 0; $row < $count ; $row++) {

    echo "<a href=".$matches[1]["$row"]." target='_blank' rel='link rel'>link title</a><br />";

}

?>

这就是我得到的:

<a href="http://www.google.com" target="_blank" rel="link rel">link title</a><br>
<a href="http://www.facebook.com" target="_blank" rel="link rel">link title</a>

我的问题是我找不到找到rel属性并将链接内容替换为title属性的方法。

有什么想法吗?

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以像获取hrefs一样获得rels和标题:

preg_match_all('/href="(.*?)"/s', $post_content, $hrefs); // get the hrefs
preg_match_all('/title="(.*?)"/s', $post_content, $titles); // get the titles
preg_match_all('/rel="(.*?)"/s', $post_content, $rels); // get the rels
preg_match_all('/>([^>]*)<\/a>/s', $post_content, $contents); // get the link contents

$count = count($hrefs[1]);

for ($row = 0; $row < $count ; $row++) {

    // Note that I've added the `href` quotes.
    echo "<a href='".$hrefs[1]["$row"]."' target='_blank' rel='".$rels[1]["$row"]."'>".$contents[1]["$row"]."</a><br />";

}

答案 1 :(得分:0)

在这里看看:https://regexr.com/40f21

我已经建立了一个正则表达式来捕获一行,例如您的示例:/<a href="(.*)" target="(.*)" rel="(.*)"\>(.*)<\/a>/isU。我添加的其他标志是U表示不满意,i表示不区分大小写。

您可以在底部的窗口中看到Google示例返回的匹配数组如下:

[0] = <a href="http://www.google.com" target="_blank" rel="1">link title 1</a> (the matched string)
[1] = http://www.google.com (the src)
[2] = _blank (the target)
[3] = 1 (the rel)
[4] = link title 1 (the link text)

请注意,这一点都不灵活,如果链接与示例中给出的格式不完全匹配,则它将不匹配。可能更好的方法是使正则表达式匹配<a> - </a>的打开和关闭,并捕获介于两者之间的所有内容。然后处理捕获的内容,并在空格处爆炸,然后再次在等值处爆炸并计算出所得到的内容。这意味着,例如,如果某个链接恰好没有目标属性,那么您仍然可以对其进行处理。

希望这会有所帮助。