0

I have a data in mysql table:

<p>aaaa</p>
<p>&nbsp;</p>
<p>asd</p>

and I need to display it like this:

aaaa asd

But I can't seem to get it right.

First I'm using this code:

$string = htmlspecialchars_decode(stripslashes($string)); // $string contains data from the table

and I tried this: (from here)

$string = trim(preg_replace('/\s+/', ' ', $string));

and also this: (from here)

$string = str_replace(array("\n", "\r"), '', $string);

but nothing works! when I use echo $string; it still shows an empty line. can anyone give a solution?

Community
  • 1
  • 1
dapidmini
  • 1,186
  • 2
  • 16
  • 26

3 Answers3

2

Try this

$x = '<p>aaaa</p>
<p>&nbsp;</p>
<p>asd</p>';
$spaces = array('&nbsp;',' ');
echo str_replace($spaces,'',strip_tags($x));
Rejoanul Alam
  • 5,365
  • 3
  • 36
  • 67
  • this was supposed to worked perfectly, but it returns multiple spaces. even though the second parameter is an empty string. why is that? – dapidmini Nov 30 '16 at 08:50
1

Can find the answer here. Or try: $line_out = preg_replace('/[\n\r]+/', '', $line_in);

Community
  • 1
  • 1
LenglBoy
  • 1,413
  • 1
  • 10
  • 23
  • 1
    this one works. thanks! I've searched google for almost an hour but I don't remember seeing that answer.. weird... – dapidmini Nov 30 '16 at 08:54
1

The line breaks are caused by the <p> tags because they are block-level elements:

Browsers typically display the block-level element with a newline both before and after the element.

If you don't want HTML tags in your string you can remove them with strip_tags():

$string = strip_tags($string); 

If you want to keep the <p> tags, you need to display them as inline elements using CSS:

p {
    display: inline; /* or display: inline-block; */
}
simon
  • 2,708
  • 1
  • 15
  • 22
  • does that mean I don't need to use htmlspecialchars_decode or something to display the data from database? I thought strip_tags() is not secure enough? – dapidmini Nov 30 '16 at 08:53
  • @dapidmini depends on where the data is coming from. If this data is user input you need to use `htmlspecialchars()` on it – simon Nov 30 '16 at 09:19