Bird
0
0

You want to safely replace all spaces in a string with underscores in PHP. Which code snippet correctly does this?

hard📝 Application Q15 of 15
PHP - String Functions
You want to safely replace all spaces in a string with underscores in PHP. Which code snippet correctly does this?
A$new = str_replace(' ', '_', $original);
B$new = substr_replace($original, '_', ' ', -1);
C$new = strtoupper(str_replace('_', ' ', $original));
D$new = trim($original, ' ');
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want to replace all spaces (' ') with underscores ('_') in the string.
  2. Step 2: Identify the correct function

    str_replace(' ', '_', $original) replaces all spaces with underscores safely.
  3. Step 3: Check other options

    substr_replace is for replacing part by position, not all spaces; strtoupper changes case; trim removes spaces only at ends.
  4. Final Answer:

    $new = str_replace(' ', '_', $original); -> Option A
  5. Quick Check:

    str_replace() replaces all occurrences [OK]
Quick Trick: Use str_replace() to swap all spaces with underscores [OK]
Common Mistakes:
  • Using substr_replace which replaces by position, not all spaces
  • Using strtoupper which changes case, not characters
  • Using trim which only removes spaces at string ends

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes