CodeBlanks Logo Icon CodeBlanks

Summary - Advanced string methods

PHP course · Beginner · Lesson 93/116

Build a CSV line parser with str_replace, substr, explode and implode.

Advanced string methods recap

In this group you learned five important string functions. str_replace() replaces a substring, substr() takes a slice, strpos() gives the position of a substring, explode() splits a string into an array, and implode() joins an array into a string.

Combined, they let you solve real tasks: parsing a CSV line, extracting a domain from an email, formatting a tag list. Now two summary tasks await: first a CSV parser, then an email domain extractor.

Exercise Parse a CSV line

Assign "Pen,Blue,12" to $csv. Use str_replace() to change 'Blue' to 'BLUE' and assign the result back to $csv. Use explode() with the ',' delimiter to assign the parts to $fields. Use implode() with the ' | ' glue to join $fields and print it with echo.

Show example solution
First assign $csv, then $csv = str_replace("Blue", "BLUE", $csv);. Then $fields = explode(",", $csv); and finally echo implode(" | ", $fields);
Example solution:
<?php
$csv = "Pen,Blue,12";
$csv = str_replace("Blue", "BLUE", $csv);
$fields = explode(",", $csv);
echo implode(" | ", $fields);

Exercise Extract the domain from an email

Assign "info@codeblanks.com" to $email. Assign the result of strpos($email, '@') to $at. Assign the result of substr($email, $at + 1) to $domain. Then print it with echo $domain;.

Show example solution
First assign $email. Then $at = strpos($email, "@");. Then $domain = substr($email, $at + 1); and finally echo $domain;
Example solution:
<?php
$email = "info@codeblanks.com";
$at = strpos($email, "@");
$domain = substr($email, $at + 1);
echo $domain;

Your string toolkit grew

Congratulations! In this summary you combined str_replace(), substr(), strpos(), explode() and implode(). You split a CSV line into an array, replaced a value and joined it back; you found the @ position in an email and extracted the domain.

These five functions appear all the time in real PHP applications. You will use them to clean form data, process file names or parse API responses. In the next group you will learn to read URL and form data with superglobals.

Test yourself

  1. Which function joins an array into a string?

    • explode
    • substr
    • str_replace
    • implode
    Show answer

    implode — Correct. implode joins; explode splits.

  2. Last four digits of the card

    $card = '4111-2222-3333-4444';
    $last = substr($card, ____);
    echo $last;
    Show answer
    $card = '4111-2222-3333-4444';
    $last = substr($card, -4);
    echo $last;

All lessons in Beginner