0

输入

$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); 

帮助表示赞赏。

4

2 回答 2

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>";      
}
于 2013-10-27T13:20:19.353 回答
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>";
于 2013-10-27T13:16:21.050 回答