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

Viewed 55

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!

3 Answers

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. The tag part therefore is not visible for display.

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;

the output then will display as:

Stack<overflow

Use htmlspecialchars with it

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

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

Related