首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将文本和图像从字符串中分离出来,并在<p>标记php中包装文本

将文本和图像从字符串中分离出来,并在<p>标记php中包装文本
EN

Stack Overflow用户
提问于 2013-10-27 12:55:07
回答 2查看 71关注 0票数 0

输入

代码语言:javascript
复制
$str = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/ipad-air-hands-on-angle.jpg"> Apple's plan to launch the iPad Air with cellular data support for T-Mobile was apparently just the start of a larger strategy. US Cellular has announced that it will offer the featherweight tablet on November 8th, while regional carriers like Bluegrass Cellular, C Spire and GCI say that they'll ...'

$str2 = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/ipad-air-hands-on-angle.jpg">Apple's plan to launch the iPad Air with cellular data support for T-Mobile was apparently just the start of a larger strategy. US Cellular has announced that it will offer the featherweight tablet on November 8th, while regional carriers like Bluegrass Cellular, C Spire and GCI say that they'll ...'

输出我需要

代码语言:javascript
复制
<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/ipad-air-hands-on-angle.jpg">
<p>Apple's plan to launch the iPad Air with cellular data support for T-Mobile was apparently just the start of a larger strategy. US Cellular has announced that it will offer the featherweight tablet on November 8th, while regional carriers like Bluegrass Cellular, C Spire and GCI say that they'll ...</p>

如何从上面的两个字符串中获得所需的输出?我试过以下几种方法,但这似乎不太好。

代码语言:javascript
复制
            $item_content = str_replace('> ', '> <p>', $item_content); 
            $item_content = str_replace('>', '> <p>', $item_content); 

我们很感激你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-27 13:16:21

使用DOMDocument

代码语言:javascript
复制
$str = '<img ... /> text ...';

$html = new DOMDocument();
$html->loadHtml($str);

$img_tag = $html->getElementsByTagName('img')->item(0)->C14N();
$text = trim($html->textContent);

然后,您可以以任何您喜欢的方式输出:

代码语言:javascript
复制
echo "{$img_tag}\n<p>{$text}</p>";
票数 1
EN

Stack Overflow用户

发布于 2013-10-27 13:20:19

您可以使用正则表达式。它将是:

代码语言:javascript
复制
$str = '<img src="http://www.blogcdn.com/www.engadget.com/media/2013/10/ipad-air-hands-on-angle.jpg"> Apple\'s plan to launch the iPad Air with cellular data support for T-Mobile was apparently just the start of a larger strategy. US Cellular has announced that it will offer the featherweight tablet on November 8th, while regional carriers like Bluegrass Cellular, C Spire and GCI say that they\'ll ...';

if(preg_match('/^(<img[\S\s]+?>)([\S\s]*)$/i', $str, $matches)) {
    $img = $matches[1];
    $text = trim($matches[2]);
    echo "$img\n<p>$text</p>";      
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19618272

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档