Yii2 编辑器小部件

Yii2 Redactor widget

我有一个基本的博客应用程序,它使用 redactor 作为输入文本的方式。但是,当上传图片时,它们会在 'body' 字段中保存为 HTML 标签。例如:

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

是保存在 'body' 字段中的内容。

这就是我检索和显示数据的方式:

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

有什么方法可以在其中添加 'if' 语句来表示

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

strstr() 在字符串中搜索字符串 http://php.net/manual/en/function.strstr.php

所以你可以试试:

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

获取标签的另一种方法可能是一些正则表达式,尽管它可能不匹配,具体取决于 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]);

这将输出string(22) "<img src="blah.jpg" />"

代码如下https://3v4l.org/4NCNs

这是正则表达式 https://regex101.com/r/m1IYpx/1/