Bird
0
0

You have a string $data = "user:john;id:12345;role:admin";. How do you extract the user name "john" using substr and strpos functions in PHP?

hard📝 Application Q15 of 15
PHP - String Functions
You have a string $data = "user:john;id:12345;role:admin";. How do you extract the user name "john" using substr and strpos functions in PHP?
Asubstr($data, 0, strpos($data, ':'));
Bsubstr($data, 5, 4);
Csubstr($data, strpos($data, ';') + 1, 4);
Dsubstr($data, strpos($data, ':') + 1, strpos($data, ';') - strpos($data, ':') - 1);
Step-by-Step Solution
Solution:
  1. Step 1: Find start position of username

    Use strpos($data, ':') to find colon after "user", add 1 to start after colon.
  2. Step 2: Find length of username substring

    Find position of first semicolon with strpos($data, ';'), subtract start position and 1 to get length.
  3. Step 3: Use substr with calculated start and length

    substr($data, start, length) extracts "john" correctly.
  4. Final Answer:

    substr($data, strpos($data, ':') + 1, strpos($data, ';') - strpos($data, ':') - 1); -> Option D
  5. Quick Check:

    Use strpos to find delimiters, substr extracts between them [OK]
Quick Trick: Use strpos to find delimiters, substr extracts between them [OK]
Common Mistakes:
  • Hardcoding start and length without dynamic positions
  • Using wrong delimiter positions
  • Extracting wrong substring part

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes