2015-10-28 50 views
2

我有回来从我的数据库,像这样一些文字:SUBSTR字符串以HTML在PHP

<span rgb(61,="" 36,="" 36);="" font-family:="" 'frutiger="" neue="" w01="" book',="" 'helvetica="" neue',="" helvetica,="" arial,="" sans-serif;="" line-height:="" 23.8px;"="">The Department of ...

我用echo html_entity_decode($item->body);来显示:

The Department of ......

但是,如果我在此内容上使用PHP substr函数,它永远不会正确显示。它将显示HTML的前x个字符,而不是HTML格式的文本。

这里是我的尝试:echo substr(html_entity_decode($item->body), 0, 5);

但它并不显示任何内容。如果我尝试像0, 200);量会显示:

The Department of Molec

但这绝对不是格式化文本的前200个字符,因为第一个字符是T

我的想法是,必须有格式然后substr,即使我不能使用它们自己使用html_entity_decode()substr()工作。

有人可以帮我吗?谢谢!

+2

向我们展示'substr'的​​尝试,以便我们解决它。 – Script47

+0

更新了我的文章。 – Nic

+0

是的,我有...... – Nic

回答

0

您将在源代码中看到输出,但它不会被渲染。源代码将显示:

echo substr(html_entity_decode($item->body), 0, 5); 
// Output: "<span" 

你可能想要做的是搜索的HTML标签的末尾,显示后5个字符,如:

$text = html_entity_decode($item->body); 
$start = strpos($text, '>') + 1; 
echo substr($text, $start, 5); 
+0

显示正确的文本,但是,我的href的中断。 – Nic

+0

然后有一种将[DOMDocument](http://php.net/manual/en/book.dom.php)阅读为可怕的方法,并通过节点和nodeValues进行解析 –

1

尝试使用此而不是html_entity_decode():

strip_tags($item->body); 

用strip_tags将删除字符串的所有HTML标签。所以你最好先对待弦乐,然后用它做点什么。