how to remove space from string containing '<' symbol in php?

784 views php
3

My string contains '<' symbol.

Example:

$str = "S t a c k < o v e r f l o w";

when i use str_replace() as

$str = str_replace(' ', '', $str);
echo $str;

The output is:

Stack

All the letters after < are not printed.

where i am wrong? Please Help!

answered question

What you are seeing is 'Stack' ... and the tool you use to see the output clips the rest (lemme guess : browser ?). In console, this works as you would expect.

It work correctly in 3v4l.org/OGcok . Because string contain < browser consider it as tag start. So use htmlspecialchars()

3 Answers

11

You could use this way:

$str = "S t a c k < o v e r f l o w";

Replace < with #

$str = str_replace('<', '#', $str);

Replace Space with No Space

$str = str_replace(' ', '', $str);

Replace # with Space

$str = str_replace('#', ' ', $str);

echo $str;

Output

Stack Overflow

Or You can Do this way if there are html atgs in the string

// Variable to check
$str = "<h1>Hello World!</h1>";

// Remove HTML tags from string
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;

Reference: W3Schools

posted this
4

The characters are not lost, and the str_replace is working fine. The problem is that when you output the resulting string the '<' is mistaken for the start of an html tag and the rest of the string (after the '<') as the tag itself for the display the tag part therefore is not visible.

You can see this if you change your code to:

$str = "S t a c k < o v e r f l o w";
$str = htmlspecialchars(str_replace(' ', '', $str));
echo $str;

this then will display as:

Stack<overflow

posted this
8

Use htmlspecialchars with it

htmlspecialchars(str_replace(' ', '', $str));

posted this

Have an answer?

JD

Please login first before posting an answer.