ฟังก์ชัน htmlentities

ฟังก์ชัน htmlentities แปลงอักขระ เป็น HTML entities ที่ตรงกัน ดูตัวอย่างเพื่อความเข้าใจที่ดีขึ้น

ฟังก์ชันนี้คล้ายกับ htmlspecialchars, อย่างไรก็ตาม ต่างกันตรงที่มันแปลง *ทั้งหมด* อักขระที่มี HTML entity อยู่

ไวยากรณ์

phphtmlentities(string $string, int $flags = ENT_COMPAT, ?string $encoding = null, bool $double_encode = true): string

ตัวอย่าง

มาแปลงสตริงที่มีแท็ก:

php<?php
  $str = '<b>text</b>';
  $res = htmlentities($str);
  
  echo $res;
?>

ผลลัพธ์จากการรันโค้ด:

php'<b>text</b>'

ตัวอย่าง

มาแปลงสตริงที่มี เครื่องหมายแอมเพอร์แซนด์:

php<?php
  $str = 'test: &';
  $res = htmlentities($str);
  
  echo $res;
?>

ผลลัพธ์จากการรันโค้ด:

php'test: &'

ดูเพิ่มเติม

  • ฟังก์ชัน html_entity_decode,
    ซึ่งดำเนินการตรงกันข้าม
  • ฟังก์ชัน htmlspecialchars,
    ซึ่งดำเนินการที่คล้ายกัน