Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 147 · Strings in Depth

Escaping and Encoding Helper Functions

A tour of PHP's smaller string helpers - htmlentities, html_entity_decode, addcslashes, quotemeta, chunk_split, crc32, quoted_printable, strspn, count_chars and str_rot13.

String Functions covers the everyday tools: strlen, substr, str_replace, trim. PHP also carries a long tail of smaller helpers that escape text for a specific target, split it into chunks, fingerprint it or measure what it is made of. You will not use them daily, but each one solves a particular problem in one line, and you will meet them in older code. This lesson groups them by purpose so you can find the right one.

A rule of thumb runs through all of them: escaping depends on where the text is going. HTML needs one kind of escaping, a regular expression another, an e-mail body a third. Always pick the function that matches the destination, and read XSS and Output Escaping for the security side.

HTML: htmlspecialchars, htmlentities and their decoders

htmlspecialchars() converts only the five characters that matter in HTML (& < > " '). htmlentities() converts those too, and also every character that has a named entity, so é becomes &eacute; and © becomes &copy;. When your page is UTF-8, which it should be, htmlspecialchars() is all you need and keeps the text readable in the source. htmlentities() is mainly useful for output that must stay pure ASCII.

The decoders go the other way. html_entity_decode() turns every entity back into a character. htmlspecialchars_decode() reverses only what htmlspecialchars() produced.

PHP HTML encoding and decoding

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the flags. Since PHP 8.1 the default flags are ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, so single quotes are escaped too. Always pass the encoding ('UTF-8') explicitly in code that may run on old configurations. And only turn double_encode off when you really are re-escaping text that may already be escaped; otherwise &amp; shown to a reader should stay &amp;amp; in the source.

Never html_entity_decode() data from a user and print it unescaped. Decoding is for turning stored or received HTML text back into plain text, and the result must be escaped again before it goes into a page.

Escaping for other targets

addcslashes

addcslashes($string, $characters) puts a backslash before each listed character. The list accepts ranges with .., so "A..Z" means every capital letter. It can also render control characters as C-style escapes (\n, \t, \x07), which is handy for debug output and log lines.

quotemeta

quotemeta() escapes the characters that have a special meaning in many shell and regex dialects: . \ + * ? [ ^ ] $ ( ). For PHP regular expressions use preg_quote() instead, because it also knows your delimiter and the PCRE-specific characters (see Regular Expressions).

PHP addcslashes and quotemeta

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

For escaping quotes and backslashes the older addslashes() exists, but do not use it to protect SQL; prepared statements from PDO Basics are the correct tool.

Splitting and transfer encodings

chunk_split($string, $length, $separator) inserts the separator after every length characters, including at the end. It was designed to wrap Base64 output into lines of 76 characters for e-mail; the defaults are 76 and "\r\n".

quoted_printable_encode() and quoted_printable_decode() handle the encoding used in mail bodies that are mostly ASCII: ordinary characters stay as they are, others become = followed by two hex digits. convert_uuencode() and convert_uudecode() implement the old Unix-to-Unix encoding, which you will see only in legacy systems.

PHP chunk_split and quoted-printable

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If you need to cut a string into an array of pieces rather than inserting separators, use str_split() or mb_str_split() from Multibyte Strings.

Checksums: crc32

crc32($string) returns a 32-bit cyclic redundancy check as an integer. It is fast and good at catching accidental corruption (a flipped bit in a download or a mistyped cache key), but it is not a security feature: anybody can craft input with a chosen CRC. On 32-bit builds the integer can come out negative, so format it with dechex() or use hash('crc32b', $s), which returns the usual 8-digit hex string. For integrity against attackers, use hash('sha256', ...) and hash_equals() as taught in Cryptography.

Measuring what a string is made of

strspn($string, $mask) counts how many characters at the start of the string consist only of characters in $mask. strcspn() is the opposite: how many characters come before the first character that is in the mask. Both accept an offset and a length. They are tiny tokenizers: you can read a run of digits or find the end of a word without a regular expression.

count_chars($string, $mode) tallies bytes. Mode 1 returns an array of byte value to count for bytes that occur; mode 3 returns a string of the distinct characters used.

str_rot13() rotates each ASCII letter by 13 places. Applying it twice restores the original. It is a toy "cipher" used to hide spoilers, never for secrets.

PHP strspn, count_chars and str_rot13

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. What is the difference between htmlspecialchars() and htmlentities()?

    For UTF-8 pages htmlspecialchars() is normally enough. htmlentities() also turns characters such as the e-acute into named entities.
  2. 2. What does chunk_split("abcdefghij", 4, "-") return?

    chunk_split() adds the separator after every chunk, including the last one, so the result ends with a dash.
  3. 3. Which function should you use to escape text that goes into a PHP regular expression?

    preg_quote() knows the PCRE special characters and your delimiter. quotemeta() targets a different set of characters.
  4. 4. What does strspn("42 apples", "0123456789") return?

    strspn() counts the characters at the start that belong to the mask. Two digits come before the space.
  5. 5. Why is crc32() a poor choice for verifying that a download was not tampered with?

    CRC32 detects accidental errors only. Use a cryptographic hash such as SHA-256 when someone may change the data on purpose.

Summary

  • htmlspecialchars() escapes the five HTML-special characters; htmlentities() escapes every named entity; the _decode functions reverse them.
  • Pick the escape function for the destination: htmlspecialchars() for HTML, preg_quote() for regex, prepared statements for SQL.
  • addcslashes() escapes chosen characters or ranges and can make control characters visible; quotemeta() escapes shell and regex metacharacters.
  • chunk_split() adds a separator after every chunk, including the last.
  • quoted_printable_* and convert_uu* are transfer encodings from the e-mail era.
  • crc32() is a fast checksum, not a security tool.
  • strspn(), strcspn() and count_chars() measure what a string contains; str_rot13() is a toy.

Next: Multibyte Strings