0

I'm looking for a solution to only display the links inside a string (my wysiwyg content) on my single page.

First of all extract all my links, and replace each links content by the links title attribute.

here is an example of what my content looks like :

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

and here is what I want to diplay on my page :

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

Here is what I've tried so far :

<?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 />";

}

?>

and here is what I get :

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

my problem is that I can't find a way to get the rel attribute, and to replace the link content by the title attribute.

any thoughts ?

thanks for your help

1
  • I would advise against using regular expressions to parse HTML, have you tried a HTML parser instead? Or better yet, what is this meant to be implementing? What problem would this be solving for the client if it worked perfectly? CPT's might be a better solution than parsing post content, or custom meta boxes/fields
    – Tom J Nowell
    Oct 1, 2018 at 16:51

1 Answer 1

2

I thought regex search may become critical so html dom parser may help. See the code below (if it helps):

<?php

$post_content = get_the_content();
$dom = new DomDocument();
$dom->loadHTML($post_content);
foreach ($dom->getElementsByTagName('a') as $item) {
   echo "<a href=".$item->getAttribute('href')." target='_blank' rel='". $item->getAttribute('rel') ."'>". $item->getAttribute('title') ."</a><br />";
}

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.