Mysql文本字段同时包含<p>和<img>:如何仅遍历<img>?

时间:2019-08-23 21:26:01

标签: php mysql image loops

我正在研究一个CRUD项目,该数据库的内容主要是通过RTF编辑器(WYSIWYG)生成的。

MySQL的其中一列称为“内容”(数据类型:文本),它由带有p和img标签的条目组成。

举个例子,该列中的每个条目如下所示:

<img src="img/1.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="2.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="img/3.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>

SQL语句之后,我可以使用PHP($ entry = row ['content'])访问上面的特定条目。

问题:如何遍历该条目中的每个图像,并访问其src?

*我需要这样做的原因是-我目前正在开发删除功能,到目前为止,我只可以删除数据库条目,而将物理文件(图像)保留在服务器上,而我希望在发布时删除它们。

3 个答案:

答案 0 :(得分:1)

按照@barmar与DOMDocument的建议尝试此操作:

$html = '<img src="img/1.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="2.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="img/3.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>';
$dom = new \DOMDocument();
$dom->loadHTML($html);
$imgs=  $dom->getElementsByTagName('img');
foreach ($imgs as $imgs) {
    echo $imgs->getAttribute('src'), PHP_EOL;
}

答案 1 :(得分:1)

您也可以使用regexp

$row = '<img src="img/1.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="2.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="img/3.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>';

preg_match_all('/src="([^"]+)"/', $row, $matches);
print_r($matches);

答案 2 :(得分:1)

您可以使用正则表达式获取此类信息


$data = '<img src="img/1.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="2.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p><img src="img/3.jpg"><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>';

preg_match_all('/src="(.*?)"/',$data,$matches);

var_dump($matches[1]);

这会给你这样的东西

array(3) {
  [0]=>
  string(9) "img/1.jpg"
  [1]=>
  string(5) "2.jpg"
  [2]=>
  string(9) "img/3.jpg"
}

请注意,我们使用$matches[1],因为它是正则表达式中的第二个偏移量捕获值。

在此处检查并使用正则表达式

https://regex101.com/r/EVXAWb/1