Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print less-than and greater-than symbols in PHP

Tags:

html

php

I am have troubles trying to print out < > symbols in HTML using PHP.

I am appending a string "<machine>" to a variable.

Example:

$output .= " <machine> ";
echo $output;

I tried using escapes, but that didn't help. Any advice?

like image 726
Howdy-Do Avatar asked Aug 02 '11 17:08

Howdy-Do


People also ask

What is htmlspecialchars() in PHP?

htmlspecialchars() Function: The htmlspecialchars() function is an inbuilt function in PHP which is used to convert all predefined characters to HTML entities. Syntax: string htmlspecialchars( $string, $flags, $encoding, $double_encode )

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

How do you check if a string contains a special character in PHP?

php function check_string($my_string){ $regex = preg_match('[@_! #$%^&*()<>?/|}{~:]', $my_string); if($regex) print("String has been accepted"); else print("String has not been accepted"); } $my_string = 'This_is_$_sample!


2 Answers

&gt; = >
&lt; = <

Or you can use htmlspecialchars.

$output .= htmlspecialchars(" <machine> ");
like image 126
Brad Christie Avatar answered Oct 05 '22 01:10

Brad Christie


If you are outputting HTML, you cannot just use < and > : you must use the corresponding HTML entities : &lt; and &gt;


If you have a string in PHP and want to automatically replace those characters by the corresponding HTML entities, you'll be interested by the htmlspecialchars() function (quoting) :

The translations performed are:

  • '&' (ampersand) becomes '&amp;'
  • '"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.
  • "'" (single quote) becomes '&#039;' only when ENT_QUOTES is set.
  • '<' (less than) becomes '&lt;'
  • '>' (greater than) becomes '&gt;'


In your case, a portion of code like this one :

$output = " ";

echo htmlspecialchars($output, ENT_COMPAT, 'UTF-8');

Would get you the following HTML code as output :

 &lt;machine&gt; 


And, just in case, if you want to encode more characters, you should take a look at the htmlentities() function.

like image 43
Pascal MARTIN Avatar answered Oct 05 '22 01:10

Pascal MARTIN