0

The following is automatically output via editor:

<a href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>

I would like to add an ID:

<a id="replace" href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>

Then use str_replace and a regular expression to find the anchors in question and replace with:

<a href="https://someurl.com/1001-web-file.pdf"><img src="https://someurl.com/1001-web-file-pdf-290x300.jpg"/></a>

What I've managed to do is:

$replace = array(
'<a id="pdfthumb" href="' => '<img src="',
'.pdf">pdfthumb</a>' => '-pdf-290x300.jpg"/></br>'
);

$text = str_replace(array_keys($replace), $replace, $text);
return $text;

This works to tear down the anchor tag and rebuild as an img. But I can't do much more. I played around with some regex to create a wildcard and realized I need to create a variable for the href to use when I rebuild the HTML, but I'm stuck.

Any insight is much appreciated :)

Jarod Thornton
  • 401
  • 1
  • 7
  • 24

2 Answers2

1

In your case, I think it should be easier if you do it on client side using javascript.

My background is not PHP but you can use the same pattern to test with your PHP code:

Input:

<a href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>

Output:

<a href="https://someurl.com/1001-web-file.pdf"><img src="https://someurl.com/1001-web-file-pdf-290x300.jpg"/></a>

var input = '<a href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>';

var pattern = /href=\"(.+)\.pdf\"/;

var match = input.match(pattern)[1];

input = input.replace(/(<a.*>).*(<\/a>)/, '$1<img src="' + match + '-pdf-290x300.jpg">$2');

console.log(input)
Tân
  • 1
  • 15
  • 56
  • 102
0

Here is translated php code of Tan javascript answer

$input = '<a href="https://someurl.com/1001-web-file.pdf">1001-web-file</a>';
preg_match('/href="(.+)\.pdf"/', $input, $m);
$match = $m[1];
$input = preg_replace('/(<a.*>).*(<\/a>)/', '$1<img src="'. $match .'-pdf-290x300.jpg">$2', $input);
echo $input;
Saf
  • 318
  • 3
  • 13
  • This works perfect! I would like to understand each part of this solution better. What does `$m[1];` accomplish? I know it's what `$m` setup in the line before it. How does `().*(<\/a>)` work? I know `.*` matches any character and you're using it to rebuild the HTML - how can I add ie `target="_blank"`? Thank you for the feedback :D – Jarod Thornton Jan 10 '20 at 00:59