开发者

Remove text from a PHP string

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?


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


preg_match('/\<img src=[^\>]+\>/', $value, $imgTag);
echo $imgTag[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] . '>';


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>');


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);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜