Skip to content
Tutorials Center
My learning

Topics

Lesson 142 of 147 ยท Practice and Review

PHP String Programs II: 12 More Classic Examples

12 more PHP string programs with output - permutations, minimum rotation, last word, cleaning special characters, truncating, text between markers, unique IDs, string to bool and == vs strcmp.

Strings are where beginners write the most code and where PHP's standard library saves the most of it. This page is the second collection of string programs after PHP Programs: 50 Classic Examples. It mixes algorithm exercises (all permutations, the lexicographically smallest rotation) with the jobs you actually do in web code: clean a user's input, shorten text for a card, grab the text between two markers, create a random identifier, convert "yes" and "off" into booleans.

All programs are complete and run on the PHP 8.5 command-line runner. Text that may contain non-English letters uses the mb_* functions from Multibyte Strings; plain ASCII examples use the ordinary ones. Related reading: String Functions, Regular Expressions and the comparison helpers.

Algorithms on strings

1. All permutations of a string

A recursive function fixes one character and permutes the rest. A generator yields results one at a time, so even a ten-letter word does not fill memory (see Generators).

PHP 1. Permutations

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.

The number of permutations grows as n!, so 10 letters already produce 3.6 million strings.

2. Minimum number of rotations that give the same string

Rotate by one character at a time until you return to the original. A trick finds it in one step: the string appears again inside s . s at position 1 or later, and that position is the answer.

PHP 2. Minimum rotations

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.

3. The lexicographically smallest rotation

Generate every rotation with substr() and keep the smallest by strcmp().

PHP 3. Smallest rotation

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.

Words and length

4. Length of the last word

Trim the text, then take the part after the last space. strrpos() finds that space, or false when there is only one word.

PHP 4. Last word length

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.

5. The first word of a string

strtok() splits by a delimiter, and strstr($s, ' ', true) returns everything before the first space. Use explode() with a limit when you also need the rest.

PHP 5. First word

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.

6. Text between two strings

Find the position of the start marker, then the end marker after it. Return null when either is missing.

PHP 6. Between two markers

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 real HTML do not use string search; parse it as shown in Parsing HTML with DOMDocument.

Cleaning and limiting

7. Remove non-printable and special characters

preg_replace() with a character class deletes what you do not want. \p{C} matches control characters, and the u flag makes the pattern work on UTF-8.

PHP 7. Clean text

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.

Never remove characters as a substitute for escaping: use htmlspecialchars() for HTML and prepared statements for SQL.

8. Limit a string to a length

mb_strimwidth() cuts to a maximum width and adds a marker such as ... that is included in the width, so the result never exceeds your limit. It counts characters, not bytes.

PHP 8. Truncate text

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.

9. Replace multiple characters at once

strtr() with an array replaces all pairs in one pass and never replaces text it just inserted. str_replace() with arrays applies the replacements one after another, which can chain.

PHP 9. Replace several characters

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.

Identifiers and conversions

10. A random unique alphanumeric string

For tokens use random_int() or random_bytes(), which are cryptographically secure. uniqid() is only a timestamp and must not be used as a secret. The output below is random, so the program prints its properties rather than the value.

PHP 10. Random identifier

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.

11. String to boolean

(bool) "false" is true, because every non-empty string is truthy except "0". For settings, forms and environment variables use filter_var() with FILTER_VALIDATE_BOOLEAN and the null-on-failure flag.

PHP 11. String to bool

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.

null from filter_var() means "not a recognizable boolean", so you can reject invalid input instead of guessing. See Type Juggling.

12. Variable name as a string, and == versus strcmp

To print the name of a variable you can use a variable variable or compact(). And since == converts numeric strings to numbers, comparing user input with it can be wrong.

PHP 12. Names and comparisons

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.

Use === for equality and strcmp() family functions only when you need ordering.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a generator a good fit for producing all permutations of a string?

    The number of permutations grows factorially. A generator lets you process each one and discard it.
  2. 2. What is the difference between str_replace() with arrays and strtr() with an array?

    str_replace() applies replacements in sequence, so swapping a and b ends with all a's. strtr() swaps correctly.
  3. 3. Which function turns the string "off" into false safely?

    A cast treats every non-empty string except "0" as true. filter_var() understands words such as off, no and false.
  4. 4. Why shouldn't you use uniqid() for password reset tokens?

    Use random_bytes() or random_int(), which come from a cryptographically secure source.

Summary

  • Generators keep permutation programs memory-friendly; the number of results grows as n!.
  • Searching s . s finds rotations in one call.
  • strrpos(), strstr(..., true), strtok() and explode() with a limit extract words; mind the false returns.
  • Clean text with Unicode-aware regex classes (\p{C}, \p{L}), but escape for output separately.
  • mb_strimwidth() truncates by characters with a marker included in the width.
  • strtr() with an array is the safe way to replace many pairs.
  • Use random_int() and random_bytes() for identifiers and filter_var() for booleans; compare with ===.

Next: PHP Date and Function Programs