String manipulation and Regular expressions Questions with Answers

12 practice questions on String manipulation and Regular expressions (PHP) with answers and step-by-step solutions. Try 10 samples below, then practise all 12 free in the AptiNest app.

Sample questions

Question 1Medium

Which function is used to strip whitespace( or other characters)from the beginning and end of string?

  1. trim_str
  2. strip_str
  3. strip
  4. trim

Answer: D. trim

Explanation

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

o " " (ASCII 32 (0x20)), an ordinary space.

o "\t" (ASCII 9 (0x09)), a tab.

o "\n" (ASCII 10 (0x0A)), a new line (line feed).

o "\r" (ASCII 13 (0x0D)), a carriage return.

o "\0" (ASCII 0 (0x00)), the NUL-byte.

o "\x0B" (ASCII 11 (0x0B)), a vertical tab.

Step-by-step solution

  1. The question asks for the function that removes whitespace or other characters from both ends of a string.
  2. Trim removes characters from the start and the end of a string.
  3. Trim_str and strip_str are not PHP functions, and strip alone is not the trimming function.
  4. The correct answer is option D, trim.

Why the other options are wrong

  • A. Trim_str is not a PHP function name; the function is trim.
  • B. Strip_str is not a PHP function name and does not trim the ends.
  • C. Strip is not the trimming function.

Tip: For trimming questions, the name is trim; ends are both sides, so think both-end cleaning.

Question 2Medium

Which of the following PCRE regular expressions best matches the string php|architect?

  1. .*
  2. \d{3}\|\d{8}
  3. [az]{3}\|[az]{9}
  4. [a-z][a-z][a-z]\|\w{9}

Answer: D. [a-z][a-z][a-z]\|\w{9}

Explanation

None of these regular expressions really represents the simplest way to match the requested string, but Answers A and D are the only ones capable of doing so. However, Answer A is too generic, since it will really match any string; therefore, Answer D is correct.

Step-by-step solution

  1. The string php|architect is three letters, a vertical bar, then nine letters.
  2. The pattern [a-z][a-z][a-z]\|\w{9} matches three lowercase letters, a literal bar and nine word characters.
  3. Option D fits the exact shape of the string, so it is the correct answer.

Why the other options are wrong

  • A. The dot-star pattern matches any text, so it is too general and does not describe this string.
  • B. This pattern needs digits, and the string has no digits.
  • C. Only the letters a and z are allowed here, so it does not match php.

Tip: Match the exact lengths and character classes; a pattern that matches anything is not the best answer.

Question 3Medium

Given a comma-separated list of values in a string, which function from the given list can create an array of each individual value with a single call?

  1. strstr()
  2. Cannot be done with a single function
  3. extract()
  4. explode()

Answer: D. explode()

Explanation

The correct answer is D. The explode function creates an array from a string breaking it up based on a specific character such as a comma. The strtok function could also be used to tokenize the string but it would require multiple calls.

Step-by-step solution

  1. explode() splits a string into an array using a delimiter like a comma.
  2. It does this in one call, making it efficient for this task.
  3. Other functions either don't split strings or need multiple steps.
  4. So explode() is the correct choice.
  5. Final answer: D (explode()).

Why the other options are wrong

  • A. strstr() finds part of a string after a needle; it does not split a list into an array.
  • B. It can be done with one function, explode(), so the claim that it cannot be done is false.
  • C. extract() creates variables from an array; it does not split a string into an array.

Tip: Use explode() to split strings into arrays with a single call.

Question 4Medium

Which of the following will not combine strings $s1 and $s2 into a single string?

  1. $s1 + $s2
  2. "{$s1}{$s2}"
  3. $s1.$s2
  4. implode(' ', array($s1,$s2))

Answer: A. $s1 + $s2

Explanation

Each of the answers will produce the desired result of concatenating the string $s1 with the string $s2, with the exception of Answer A. In PHP, the plus operator (+) does not combine two strings together as it does in other languages, such as Java or Javascript.

Step-by-step solution

  1. The question asks which option does not join the two strings into one string.
  2. In PHP the plus sign adds numbers; it does not join strings.
  3. $s1 + $s2 does not join the strings, while the other three do, so option A is the answer.

Why the other options are wrong

  • B. Braces inside double quotes put both variables into one new string.
  • C. The dot operator joins the two strings.
  • D. Implode with a space puts both strings into one string, with a space between them.

Tip: In PHP the dot operator joins strings; the plus sign is for numbers.

Question 5Medium

What happens if you add a string to an integer using the + operator?

  1. The interpreter outputs a type mismatch error
  2. The string is converted to a number and added to the integer
  3. The string is discarded and the integer is preserved
  4. The integer and string are concatenated together in a new string

Answer: B. The string is converted to a number and added to the integer

Explanation

Naturally, the string is converted to a number (or zero if such conversion cannot take place) and added to the integer using arithmetic addition. Answer B is correct.

Step-by-step solution

  1. The question asks what happens when a string is added to an integer with the plus operator.
  2. PHP converts the string to a number, using zero if it cannot be read as a number.
  3. The converted number is added to the integer, so option B is the answer.

Why the other options are wrong

  • A. PHP converts the string rather than raising a type mismatch error here.
  • C. The string is not discarded; it is converted to a number and added.
  • D. Joining strings uses the dot operator, not the plus operator.

Tip: In PHP the plus operator always does arithmetic; use the dot operator to join strings.

Question 6Medium

Which of the following functions is most efficient for substituting fixed patterns in strings?

  1. preg_replace()
  2. str_replace()
  3. str_ireplace()
  4. substr_replace()

Answer: B. str_replace()

Explanation

Both str_ireplace() and preg_replace() have more expensive (and flexible) matching logic, so you should only use them when your problem requires it. substr_replace() requires you to know the offsets and lengths of the substrings you want to replace, and is not sufficient to handle the task at hand.

Step-by-step solution

  1. str_replace() directly replaces all occurrences of a substring.
  2. It does not require complex matching logic like preg_replace().
  3. It is efficient for fixed pattern substitution.
  4. substr_replace() needs exact positions and lengths, making it less flexible.
  5. str_ireplace() handles case-insensitive matches, which is more complex.
  6. Therefore, str_replace() is the most efficient for fixed patterns.

Why the other options are wrong

  • A. preg_replace uses regular expressions, which need more work than a fixed string match.
  • C. str_ireplace ignores case, which adds work, so it is not the most efficient for fixed patterns.
  • D. substr_replace replaces by position and length, not by matching a pattern in the string.

Tip: Use str_replace() for straightforward string replacements without advanced matching.

Question 7Medium

Given a variable $email containing the string user@example.com, which of the following statements would extract the string example.com?

  1. substr($email, strpos($email, "@"));
  2. strstr($email, "@");
  3. strchr($email, "@");
  4. substr($email, strpos($email, "@")+1);

Answer: D. substr($email, strpos($email, "@")+1);

Explanation

The substr function is used to return a portion of a string, while the strpos function is good for finding a particular substring within a string. Used together, they can extract the required information. It is important to realize that former is zero-indexed while the latter is not, requiring a +1 offset to be added. That's why Answer D is correct.

Step-by-step solution

  1. The string user@example.com must be cut just after the @ sign.
  2. Strpos finds the @ sign at position 4, counting from zero.
  3. Substr from position 4 gives @example.com, so one more must be added to skip the @.
  4. Substr with strpos plus 1 gives example.com; the correct answer is option D.

Why the other options are wrong

  • A. This starts at the @ sign, so the result is @example.com.
  • B. Strstr returns text from the @ sign onward, so the result is @example.com.
  • C. Strchr is an alias of strstr, so it also keeps the @ sign.

Tip: To drop a delimiter, add 1 to its position before taking the substring.

Question 8Medium

The __ function can be used to compare two strings using a case-insensitive binary algorithm

  1. strcmp()
  2. stricmp()
  3. strcasecmp()
  4. stristr()

Answer: C. strcasecmp()

Explanation

The definition describes the strcasecmp function therefore, Answer C is correct.

Step-by-step solution

  1. The question asks for the function that compares two strings ignoring case, using a binary-safe method.
  2. Strcmp compares case-sensitively, so it does not ignore case.
  3. Strcasecmp compares two strings ignoring case and is binary safe.
  4. The correct answer is option C, strcasecmp.

Why the other options are wrong

  • A. Strcmp is case-sensitive, so it does not ignore case.
  • B. Stricmp is not a standard PHP string comparison function.
  • D. Stristr searches for a substring and returns text; it does not compare two strings.

Tip: Case-insensitive PHP string functions usually have ca in their name, as in strcasecmp.

Question 9Medium

Which of the following functions can be used to convert the binary data stored in a string into its hexadecimal representation?

  1. encode_hex()
  2. pack()
  3. hex2bin()
  4. bin2hex()

Answer: D. bin2hex()

Explanation

bin2hex() converts the binary data in a string to its hexadecimal representation. pack() builds binary data from values (pack('H*') goes from hex to binary), so it is not the answer.

Step-by-step solution

  1. The need is to convert binary data in a string to hexadecimal.
  2. bin2hex() does exactly this.
  3. pack() builds binary from values and hex2bin() goes from hex to binary, so neither is the answer.
  4. So the answer is bin2hex(): option D.

Why the other options are wrong

  • A. encode_hex() is not a PHP function.
  • B. pack() builds binary data from values; it is not the hex conversion.
  • C. hex2bin() goes the other way, from hex to binary.

Tip: bin2hex() and hex2bin() are a matching pair, one for each direction.

Question 10Medium

Assume $comment contains a string. Which PHP statement prints out the first 20 characters of $comment followed by three dots (.)?

  1. print substr($comment, 20). '...';
  2. print substr_replace($comment,'...', 20);
  3. print substr($comment, 20, strlen($comment)). '...';
  4. print substr_replace($comment, 20, '..';

Answer: B. print substr_replace($comment,'...', 20);

Explanation

substr_replace() function is used to replace substring of string with given characters.

Step-by-step solution

  1. Substr_replace replaces part of a string, starting at a position, with new text.
  2. substr_replace($comment, '...', 20) keeps the first 20 characters and replaces the rest with three dots.
  3. So option B prints the first 20 characters followed by three dots, which is the answer.

Why the other options are wrong

  • A. Substr from position 20 gives the text after the first 20 characters, not the first 20.
  • C. Substr with 20 and strlen takes characters from position 20 onward, not the first 20.
  • D. The arguments are in the wrong order and a closing bracket is missing, so it is a syntax error.

Tip: Substr_replace with only a start position replaces everything from that position to the end.

Practise all 12 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all PHP topics · All topics