1

I have the following code being echoed:

[caption id="attachment_13" align="alignnone" width="235" caption="Event 1"]
   <img src="image.png" />
[/caption] 

I only want the img tag to be echoed.

I've tried using <?php echo strip_tags($value, '<img>'); ?> but because the [caption] tag isn't actually a proper HTML tag I don't know how to remove it. Is there a function which will remove the text from a string?

Would str_replace work?

5 Answers 5

2

usually, regular expression is not recommended for HTML parsing. But if you just want something quick, you can use:

<?php

$s = '[caption id="attachment_13" align="alignnone" width="235" caption="Event 1"]
   <img src="image.png" />
[/caption] ';

if (preg_match('/<img[^>]*>/', $s, $matches)) echo $matches[0];

?>

output:

<img src="image.png" />
Sign up to request clarification or add additional context in comments.

1 Comment

This worked great. The problem was that the string wasn't being parsed by Wordpress. To parse the caption tag, you need to add this code: apply_filters('the_content', $value);
0
preg_match('/\<img src=[^\>]+\>/', $value, $imgTag);
echo $imgTag[0];

1 Comment

That'll output Array, so, if there's just one match use echo $imgTag[0];
0

Try

$str = "[caption id="attachment_13" align="alignnone" width="235" caption="Event 1"]
   <img src="image.png" />
[/caption] ";
$arr = explode ( '<img' , $str);
$arr2 = explode ( '>' , $arr[1]);

echo '<img' . $arr2[0] . '>';

Comments

0

You could, however, change the [] with <> and then do the strip_tags

$replaceThis = array('[', ']');
$withThis = array('<', '>');
echo strip_tags(str_replace($replaceThis, $withThis, $value), '<img>');

Comments

0

try some regexp : http://www.php.net/manual/en/function.preg-replace.php

something like that something should work with minimum adaptation (i don't work with PHP since a long long long time xD) :

<?php
$pattern = '/.*(<img[^>]+)>.*/';
$remplacement = '$1';
echo preg_replace($pattern, $replacement, $value);
?>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.