5 String Processing And Regular Expressions

Web Technology II · Unit 5

String Processing and Regular Expressions

Exam-focused notes for String Processing and Regular Expressions (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 4 solved past questions from this unit.

String Processing and Regular Expressions in short

Text handling is a big part of web programming. This chapter covers regular expressions, splitting and joining strings, comparing strings, and reading CSV text.

String Processing and Regular Expressions: notes

String patterns and regular expressions

A regular expression (regex) is a pattern that describes a set of strings. It is used to search, match, validate and replace text. PHP uses the PCRE style, and the pattern is written between delimiters such as / /.

Main pattern symbols:

SymbolMeaning
.any one character
^ and $start and end of the string
*, +, ?zero or more, one or more, zero or one
{n,m}between n and m times
[abc], [a-z]one character from the set or range
\d, \w, \sdigit, word character, space
( )group
|or

Main functions:

  • preg_match($pattern, $str, $matches) finds the first match.
  • preg_match_all() finds all matches.
  • preg_replace($pattern, $new, $str) replaces matches.
  • preg_split() splits by a pattern.
<?php
$email = "[email protected]";
if (preg_match('/^[\w.+-]+@[\w-]+\.[a-z]{2,}$/i', $email)) {
    echo "Valid email";
}

$phone = "98-41-234567";
echo preg_replace('/\D/', '', $phone);   // 9841234567

preg_match('/(\d{4})-(\d{2})-(\d{2})/', "Date: 2026-10-31", $m);
echo $m[1];   // 2026

String exploding and imploding

explode($separator, $string) splits a string into an array. implode($glue, $array) joins an array into a string. join() is another name for implode().

<?php
$csv = "apple,mango,banana";
$items = explode(",", $csv);
print_r($items);              // apple, mango, banana

$text = implode(" | ", $items);
echo $text;                   // apple | mango | banana

print_r(explode(",", $csv, 2));   // limit to 2 parts

A common use is to split a sentence into words and count them: count(explode(" ", $sentence)).

What this unit covers

  • String patterns and regular expressions
  • String exploding and imploding
  • String comparison and approximate equality
  • Character access in strings
  • String manipulation functions
  • CSV file parsing

Character access in strings

2082 · 5 marks

Write a program that will read your name as input string. Access and display the individual characters in the name string. [5]

A PHP string is an indexed sequence of characters, and a single character is reached with square brackets exactly as an array element is, so $name[0] is the first character. strlen() returns the length, therefore a counting loop running from 0 up to strlen($name) - 1 visits every position in turn...

Open this answer on its own page →

String exploding and imploding

2081 · 5 marks

What is exploding and imploding of strings? Illustrate with an example. [5]

Show solved answer

Exploding and Imploding of Strings in PHP


1. Exploding a String

Exploding means splitting a string into an array based on a specified delimiter/separator. In PHP, this is done using the built-in explode() function.

Syntax:

explode(separator, string, limit)
  • separator - the delimiter used to split the string (required)
  • string - the input string to be split (required)
  • limit - maximum number of elements in the array (optional)

Example:

<?php
    $str = "Apple,Banana,Mango,Orange";
    $fruits = explode(",", $str);

    print_r($fruits);
?>

Output:

Array
(
    [0] => Apple
    [1] => Banana
    [2] => Mango
    [3] => Orange
)

Here, the string is split at every comma , and each part becomes an element of the array.


2. Imploding a String

Imploding means joining array elements into a single string using a specified separator/glue. In PHP, this is done using the built-in implode() function (also called join()).

Syntax:

implode(separator, array)
  • separator - the string placed between each array element (required)
  • array - the array whose elements are to be joined (required)

Example:

<?php
    $fruits = array("Apple", "Banana", "Mango", "Orange");
    $str = implode(" - ", $fruits);

    echo $str;
?>

Output:

Apple - Banana - Mango - Orange

Here, the array elements are joined together with - as the separator to form a single string.


Summary Table

Featureexplode()implode()
PurposeSplits a string into an arrayJoins an array into a string
InputStringArray
OutputArrayString
Also known asSplitJoin

Key Point: explode() and implode() are inverse operations of each other. Explode breaks a string apart; implode brings array pieces together.

Open this answer on its own page →

String comparison and approximate equality

2080 · 5 marks

How is the approximate equality of two strings done in PHP? Write a program to demonstrate it. [5]

In PHP, approximate equality of two strings is performed using the double equals operator (==) with type juggling, or more specifically, the concept of approximate/loose comparison. However, for string similarity/approximate matching, PHP provides the built-in function: The most common approaches...

Open this answer on its own page →

String patterns and regular expressions

0 · 5 marks

Write a PHP program to illustrate string patterns using regular expression. [5]

Function Purpose ------ pregmatch() Match a pattern (returns true/false) pregmatchall() Find all matches pregreplace() Replace matched pattern pregsplit() Split string by pattern --- --- --- Pattern Meaning ------ ^ Start of string

Open this answer on its own page →