Getting only text from html

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
andrecj
Forum Newbie
Posts: 3
Joined: Mon May 07, 2012 10:02 am

Getting only text from html

Post by andrecj »

Hello,

I am wondering if it is possibble to only get the text content from this syntax.

Code: Select all

<p>thisss is a test.<img alt="" src="/userfiles/images/Fotos-0248.jpg" style="width: 300px; height: 225px; " /></p>
In this case will only get

Code: Select all

<p>thisss is a test.</p>
(this is what my db save, then I use a query to show the content to the user).


Regards
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Getting only text from html

Post by requinix »

But that's not "only the text content". I'm thinking you want either:
1. the root tag with its text content
2. that HTML without the <img> tag.
andrecj
Forum Newbie
Posts: 3
Joined: Mon May 07, 2012 10:02 am

Re: Getting only text from html

Post by andrecj »

Yes that's it , I was thinking that was a function to only get the text, from an html tag, without the <img> tag and other tags...

While I was searching for some function (couldn't find anything...), I made this:

Code: Select all

function noimg($str){
                             $loop=substr_count($str,"<img");
                             for($x=0;$x<$loop;$x++) {
                                                                  $begin = strpos($str,"<img");
                                                                  $end = strpos($str,"/>",$begin);
                                                                  $strb=substr($str,0,$begin);
                                                                  $stre=substr($str,$end+2);
                                                                  $str=$strb.$stre;
                                                                  } return $str;
                              }
This will only remove the images from the string...
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Getting only text from html

Post by requinix »

Grab the inner content (inside the <p>) and strip_tags it.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: Getting only text from html

Post by tr0gd0rr »

If you use HTML Purifier, you can indicate in the options exactly what tags and attributes to allow and which to strip out. It is a full HTML parser that should not be fooled by malicious HTML (i.e. Cross Site Scripting).
andrecj
Forum Newbie
Posts: 3
Joined: Mon May 07, 2012 10:02 am

Re: Getting only text from html

Post by andrecj »

Hmmm alright, I'm going to test it. Appreciated for your help.
Post Reply