2

I have some text that comes back from my database like so:

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

I use echo html_entity_decode($item->body); to display:

The Department of ...

However, if I use the PHP substr function on this content it never displays correctly. It will display the first x characters of HTML and not the HTML formatted text.

Here's what I tried: echo substr(html_entity_decode($item->body), 0, 5);

But it doesn't display anything. If I try an amount like 0, 200); it will display:

The Department of Molec

But this is most definitely not the first 200 characters of the formatted text because the first character is T.

My idea is that there must be way to format and then substr, even though I can't get it to work using html_entity_decode() and substr() by themselves.

Can anybody help me out here? Thanks!

3
  • 2
    Show us your attempt of substr so we can fix it. Commented Oct 28, 2015 at 21:39
  • But it's not. 0, 1); should output T. Instead it outputs <. Commented Oct 28, 2015 at 21:47
  • 1
    PHP doesn't know what html is. HTML is just text, and PHP will treat it like it does any OTHER text. If you want just the text nodes of an html snippet, then it's up to YOU to extract those text snippets. That means using proper HTML-aware tools, like DOM. Commented Oct 28, 2015 at 21:51

2 Answers 2

2

Try to use this instead of html_entity_decode():

strip_tags($item->body);

strip_tags removes all HTML tags from the string. So you better of treating the string and then do something with it.

Sign up to request clarification or add additional context in comments.

Comments

0

You will see the output in the source code, but it is not beeing rendered. The source code will show:

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

What you probably want to do is search for the end of the html-tag, and display 5 characters after that, like:

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

2 Comments

Displays the correct text, however, my href's break.
Then there is the terrible way of reading it as a DOMDocument, and parse through nodes and nodeValues

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.