删除部分字符串PHP
问题描述:
我正在处理一些RSS数据。我正在尝试删除字符串的某些部分。删除部分字符串PHP
的字符串是这样的:
<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>
我只想显示:
**THIS IS THE INFO I ACTUALLY WANT TO KEEP**
或
**<p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>**
我使用PHP和想存储的值一个变量。
非常感谢您的帮助。
答
使用strip_tags,如果你想保持p标签,添加第二个参数<p>
<?php
//without p tag
echo strip_tags('<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>');
echo "\n";
//with p tag
echo strip_tags('<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>', '<p>');
和输出:
[email protected]:~$ php test.php
THIS IS THE INFO I ACTUALLY WANT TO KEEP
<p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>
答
试试这个
$str = '<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>';
preg_match('~<p>(.*?)</p>~', $str, $matches);
var_dump($matches);
答
使用strip_tags:
$text = '<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>';
echo strip_tags($text);
答
我认为你正在寻找比XHTML标签等文本信息,你可以做到这一点在PHP的示例 -
$text = '<description><![CDATA[<div style="float:right;margin:0 0 1ex 1ex"><a href="/link/123" rel="nofollow" title="Link: www.example.com/testing-information"><img src="http://www.example.com/a/100/1000.jpg?hash=a38232k" alt="More info here"/></a></div><p>THIS IS THE INFO I ACTUALLY WANT TO KEEP</p>';
echo strip_tags($text);
echo "\n";
使用'
strip_tags($text)
strip_tags' –看起来像XML的一部分,尝试使用[simplexml_load_string](http://www.php.net/manual/en/function.simplexml-load-string.php)上的完整字符串 – bansi