将字符串中的文本和图像分开,并在<p>标记php </p>中包装文本

时间:2013-10-27 12:55:07

标签: php

输入

$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 ...'

输出我需要

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

如何从上面的2个字符串中获取所需的输出?我尝试了以下但是这看起来并不那么好。

            $item_content = str_replace('> ', '> <p>', $item_content); 
            $item_content = str_replace('>', '> <p>', $item_content); 

非常感谢帮助。

2 个答案:

答案 0 :(得分:1)

使用DOMDocument

$str = '<img ... /> text ...';

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

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

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

echo "{$img_tag}\n<p>{$text}</p>";

答案 1 :(得分:1)

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

$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>";      
}