0

I want to use htmlspecialchars but to only convert the greater (>) and lesser (<) signs. I do not want to convert the single, double and '&' signs. I tried and searched alot but could not find the answer. Please help.

Ajmal Razeel
  • 1,663
  • 7
  • 27
  • 51
  • 1
    Are you sure you want to do that? Can you explain why? Raw ampersands are invalid HTML – Eric Aug 01 '17 at 22:08

3 Answers3

2
$replace = array('<' => '&lt;', '>' => '&gt;');
$string=strtr($string, $replace);

Differences between str_replace and strtr are discussed here: When to use strtr vs str_replace?

iXCray
  • 1,072
  • 8
  • 13
0

Try using a str_replace() function with an array as 'needle in the haystack':

$search_for_lt = array("<","&lt;");
$string = str_replace($search_for_lt, "replacement here, can be empty", $string);
$search_for_gt = array(">","&lt;");
$string = str_replace($search_for_gt, "replacement here, can be empty", $string);

Can you confirm it is working as expected?

Cagy79
  • 1,610
  • 1
  • 19
  • 25
0

Why not just replace only those characters using str_replace then?

$result = str_replace(['<', '>'], ['&lt;', '&gt;'], $string);
Mogzol
  • 1,405
  • 1
  • 12
  • 18