Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How To Get All Occurrences of a string php between delimiters

How To Get All Occurrences of a string php between delimiters

Using the following function we get all occurences from a string which are between two delimiters. As you can see all paramters you have to pass is the string where the function will serach, the start delimiter and the final delimiter.

Get all occurences of a string php

public function getContents($str, $startDelimiter, $endDelimiter) {
    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = $contentStart = $contentEnd = 0;
    while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
      $contentStart += $startDelimiterLength;
      $contentEnd = strpos($str, $endDelimiter, $contentStart);
      if (false === $contentEnd) {
        break;
      }
      $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
      $startFrom = $contentEnd + $endDelimiterLength;
    }
  
    return $contents;
    }

The output of this function will be an array with all occurences that are between your delimiters. Let me know if it is what you are looking for.

Leave a Reply

avatar
  Subscribe  
Notify of