PHP Program for Naive Algorithm for Pattern Searching

PHP (Hypertext Preprocessor) is a widely used server-side scripting language for web development. The Naive algorithm, also known as the Brute Force algorithm, is a simple pattern searching technique that finds occurrences of a pattern within a text by comparing characters one by one.

What is Naive Algorithm?

The Naive algorithm is called "naive" because it doesn't employ sophisticated data structures or advanced techniques. It works by iterating through the text and comparing each character with the corresponding character in the pattern. If a mismatch occurs, it moves to the next position in the text and starts the comparison again.

Text: A B A A B A B A Pattern: A B A A 0 B 1 A 2 A 3 B 4 A 5 B 6 A 7 A B A Match found at index 0!

Algorithm Steps

The Naive algorithm follows these steps

  1. Start from the first character of the text
  2. Compare the pattern with the text starting at the current position
  3. If all characters match, record the starting index
  4. Move to the next character in the text and repeat
  5. Continue until the end of the text is reached

PHP Implementation

Here's a complete PHP implementation of the Naive pattern searching algorithm

<?php
function naivePatternSearch($text, $pattern) {
    $textLength = strlen($text);
    $patternLength = strlen($pattern);
    $foundIndexes = array();
    
    // Check each position in text
    for ($i = 0; $i <= $textLength - $patternLength; $i++) {
        $j = 0;
        
        // Compare pattern with text at current position
        while ($j < $patternLength && $text[$i + $j] == $pattern[$j]) {
            $j++;
        }
        
        // If complete pattern matches, store the index
        if ($j == $patternLength) {
            $foundIndexes[] = $i;
        }
    }
    
    return $foundIndexes;
}

// Test the algorithm
$text = "ABAAABABABAAB";
$pattern = "ABA";

$results = naivePatternSearch($text, $pattern);

echo "Text: " . $text . "<br>";
echo "Pattern: " . $pattern . "<br>";
echo "Pattern found at positions: ";

if (!empty($results)) {
    echo implode(", ", $results);
} else {
    echo "No matches found";
}
?>
Text: ABAAABABABAAB
Pattern: ABA
Pattern found at positions: 2, 5, 7, 10

Time Complexity

The Naive algorithm has a time complexity of O(m × n), where m is the length of the pattern and n is the length of the text. In the worst case, it may need to check every character of the text against every character of the pattern.

Conclusion

The Naive algorithm provides a straightforward approach to pattern searching in PHP. While it's not the most efficient for large texts, it's easy to understand and implement, making it suitable for educational purposes and small-scale applications.

Updated on: 2026-03-15T10:35:12+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements