Search code examples
phpimageyii2thumbnailsredactor

Yii2 Redactor widget


I have a basic blog application which uses redactor as the means for inputting text. However when images are uploaded they are saved as HTML tags in the 'body' field. For example:

<p>Test blog post</p><p><img src="/uploads/11/4d3ca0098c-dsc9011.jpg"></p>

is what gets saved in the 'body' field.

This is how I am retrieving and displaying the data:

 foreach($dataProvider->getModels() as $post){
    echo Html::a('<div class="well well-sm" id="inner"><h3>'.$post->subject.'</h3>', '/post/view?id=' .$post->id);
    echo 'Posted By: ' .$post->user->username . ' <br/><i class = "glyphicon glyphicon-time"></i> '.Yii::$app->formatter->asDatetime($post->updated_at)  . '<br/>Views: ' .$post->view_count .'</div>'; 
}   

Is there a way I can add an 'if' statement in there to say

if ($post->body contains < img > tag) { display < img > }


Solution

  • strstr() searcjhes for a string within a string http://php.net/manual/en/function.strstr.php

    So you could try:

    if (strstr($post->body, '<img ')) {
    

    Another way to grab the tag could be some regex, although it could mismatch depending on the HTML:

    <?php
    
    $html = '<html>
    <head>
    <etc />
    </head>
    <body>
    <div><img src="blah.jpg" /></div><br />
    </body>
    </html>';
    
    $regex = '#<img .*?\/>#';
    
    preg_match($regex, $html, $matches);
    
    var_dump($matches[0]);
    

    Which will output string(22) "<img src="blah.jpg" />"

    Here's the code https://3v4l.org/4NCNs

    Here's the regex https://regex101.com/r/m1IYpx/1/