Introduction

Hello, and welcome to our analysis lesson. In this lesson, we will tackle a common problem in string manipulations with PHP. We will learn how to find all occurrences of a substring within a larger string. The techniques you will master today can be utilized in numerous situations, such as text processing and data analysis. Are you ready to get started? Let's jump right in!

Task Statement and Description

Here is this unit's task: We have two arrays of strings, both of identical lengths — the first containing the "original" strings and the second containing the substrings. Our goal is to detect all occurrences of each substring within its corresponding original string and, finally, return an array that contains the starting indices of these occurrences. Remember, the index counting should start from 0.

Example

Let's consider the following arrays:

  • Original Array: ["HelloWorld", "LearningPHP", "GoForBroke", "BackToBasics"]
  • Substring Array: ["loW", "ear", "o", "Ba"].

The following are the expected outputs:

  • In "HelloWorld", "loW" starts at index 3.
  • In "LearningPHP", "ear" starts at index 1.
  • In "GoForBroke", "o" appears at indices 1, 3, and 7.
  • In "BackToBasics", "Ba" starts at indices 0 and 6.

Thus, when findSubString(["HelloWorld", "LearningPHP", "GoForBroke", "BackToBasics"], ["loW", "ear", "o", "Ba"]) is invoked, the function should return:

[
    "The substring 'loW' was found in the original string 'HelloWorld' at position(s) 3.",
    "The substring 'ear' was found in the original string 'LearningPHP' at position(s) 1.",
    "The substring 'o' was found in the original string 'GoForBroke' at position(s) 1, 3, 7.",
    "The substring 'Ba' was found in the original string 'BackToBasics' at position(s) 0, 6."
]

Although this task may seem fairly straightforward, it can prove challenging. However, don't worry! We will break it down step by step.

Step-by-Step Solution: Step 1, Creating the Output Array
Step 2: Pairing Strings and Locating First Occurrence
Step 3: Locating Subsequent Occurrences
Step 4: Formatting and Storing the Results
The Complete Solution
Lesson Summary

Well done! You've mastered a central operation in string manipulations in PHP — finding all occurrences of a substring in another string. Keep in mind that this algorithm has numerous applications in real-world scenarios. Now that we have intricately dissected the problem and provided a detailed solution, I encourage you to practice more. Future exercises will help you hone your skills further. Keep on coding and exploring!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal