Get string between - Find all occurrences PHP

preg_match_all online
preg_match in php
php search for multiple values in string
php preg_match multiple matches
php preg-match all links
regex match all occurrences
php preg_match_all html tags
find all occurrences of a substring in a string php

I found this function which finds data between two strings of text, html or whatever.

How can it be changed so it will find all occurrences? Every data between every occurrence of $start [some-random-data] $end. I want all the [some-random-data] of the document (It will always be different data).

function getStringBetween($string, $start, $end) {
    $string = " ".$string;
    $ini = strpos($string,$start);
    if ($ini == 0) return "";
    $ini += strlen($start);
    $len = strpos($string,$end,$ini) - $ini;
    return substr($string,$ini,$len);

One possible approach:

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) {
    $contents[] = substr($str, $contentStart, $contentEnd - $contentStart);
    $startFrom = $contentEnd + $endDelimiterLength;

  return $contents;


$sample = '<start>One<end>aaa<start>TwoTwo<end>Three<start>Four<end><start>Five<end>';
print_r( getContents($sample, '<start>', '<end>') );
    [0] => One
    [1] => TwoTwo
    [2] => Four
    [3] => Five


PHP Find all occurrences of a substring in a string, Without using regex, something like this should work for returning the string positions: $html = "dddasdfdddasdffff"; $needle = "asdf"; $lastPos  PHP stripos (or mb-stripos) finds the position of the first occurrence of a (case-insensitive) substring in a string. How to find all occurrences?. Here is a solution:

You can do this using regex:

function getStringsBetween($string, $start, $end)
    $pattern = sprintf(
    preg_match_all($pattern, $string, $matches);

    return $matches[1];

substr_count - Manual, substr_count — Count the number of substring occurrences. Description ¶. substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] ) : int. Returns the position of the last occurrence of a string inside another string, or FALSE if the string is not found. Note: String positions start at 0, and not 1. PHP Version: 4+ Changelog: As of PHP 5.0, the find parameter may now be a string of more than one character The start parameter was added in PHP 5.0

I love to use explode to get string between two string. this function also works for multiple occurrences.

function GetIn($str,$start,$end){
    $p1 = explode($start,$str);
        $p2 = explode($end,$p1[$i]);
        $p[] = $p2[0];
    return $p;

preg_match_all - Manual, Searches subject for all matches to the regular expression given in pattern and puts The pattern to search for, as a string. subject. The input string. matches. Array of all matches in Example #1 Getting all phone numbers out of some text. If you want a function to return all text in a string up to the Nth occurrence of a substring, try the below function. Works in PHP >= 5. (Pommef provided another sample function for this purpose below, but I believe it is incorrect.)

I needed to find all these occurences between specific first and last tag and change them somehow and get back changed string.

So I added this small code to raina77ow approach after the function.

        $sample = '<start>One<end> aaa <start>TwoTwo<end> Three <start>Four<end> aaaaa <start>Five<end>';
        $sample_temp = getContents($sample, '<start>', '<end>');
        $i = 1;
        foreach($sample_temp as $value) {
            $value2 = $value.'-'.$i; //there you can change the variable
            $i = ++$i;
        echo $sample;

Now output sample has deleted tags and all strings between them has added number like this:

One-1 aaa TwoTwo-2 Three Four-3 aaaaa Five-4

But you can do whatever else with them. Maybe could be helpful for someone.

strpos - Manual, Downloads · Documentation · Get Involved · Help strpos — Find the position of the first occurrence of a substring in a string. Description ¶. strpos ( string $​haystack , mixed $needle [, int $offset = 0 ] ) : int the first occurrence of a string; strpbrk() - Search a string for any of a set of characters; substr() - Return part of a string  The first works on a string and the second works on a single-level array of strings, treating it as a single string for replacement purposes (any needles split over two array elements are ignored). Can be used for formatting dynamically-generated HTML output without touching the original generator: e.g. add a newLine class tag to every third item in a floated list, starting with the fourth item.

I also needed the text outside the pattern. So I changed the answer from raina77ow above a little:

function get_delimited_strings($str, $startDelimiter, $endDelimiter) {
    $contents = array();
    $startDelimiterLength = strlen($startDelimiter);
    $endDelimiterLength = strlen($endDelimiter);
    $startFrom = $contentStart = $contentEnd = $outStart = $outEnd = 0;
    while (false !== ($contentStart = strpos($str, $startDelimiter, $startFrom))) {
        $contentStart += $startDelimiterLength;
        $contentEnd = strpos($str, $endDelimiter, $contentStart);
        $outEnd = $contentStart - 1;
        if (false === $contentEnd) {
        $contents['in'][] = substr($str, $contentStart, $contentEnd - $contentStart);
        $contents['out'][] = substr($str, $outStart, $outEnd - $outStart);
        $startFrom = $contentEnd + $endDelimiterLength;
        $outStart = $startFrom;
    $contents['out'][] = substr($str, $outStart, $contentEnd - $outStart);
    return $contents;


    $str = "Bore layer thickness [2 mm] instead of [1,25 mm] with [0,1 mm] deviation.";
    $cas = get_delimited_strings($str, "[", "]");


array(2) { 
    ["in"]=> array(3) { 
        [0]=> string(4) "2 mm" 
        [1]=> string(7) "1,25 mm" 
        [2]=> string(6) "0,1 mm" 
    ["out"]=> array(4) { 
        [0]=> string(21) "Bore layer thickness " 
        [1]=> string(12) " instead of " 
        [2]=> string(6) " with " 
        [3]=> string(10) " deviation" 

str_replace - Manual, str_replace — Replace all occurrences of the search string with the replacement count. If passed, this will be set to the number of replacements performed. Deleting all occurrences of an elements in PHP: Here, we are going to learn how to remove/delete all occurrences of a given element from an array in PHP? Submitted by Bhanu Sharma, on August 10, 2019 Given an array and we have to remove all occurrences of an element from it. array_diff() function

strrchr - Manual, strrchr — Find the last occurrence of a character in a string. Description ¶. strrchr ( string $haystack , mixed $needle ) : string get everything after last newline Find the starting indices of the substrings in string (S) which is made by concatenating all words from a list(L) Rearrange given string to maximize the occurrence of string t; Reverse the substrings of the given String according to the given Array of indices; Arrange a binary string to get maximum value within a range of indices

PHP substr_count() Function, PHP String Reference. Example. Count the number of times "world" occurs in the string: <?php The substr_count() function counts the number of times a substring occurs in a string. Note: The Using all parameters: <?php Get Certified »  SUBSTRING_INDEX() function. MySQL SUBSTRING_INDEX() returns the substring from the given string before a specified number of occurrences of a delimiter. The substring returned from the left of the final delimiter when the specified number is a positive number and from the right of the final delimiter when the specified number is a negative number.

PHP strpos() Function, Example. Find the position of the first occurrence of "php" inside the string: <?php echo strpos("I love php, I love php too!","php"); ?> Try it Yourself »  DECLARE @termToFind CHAR(1) = 'X' DECLARE @string VARCHAR(40) = 'XX XXX X XX' SET @string += '.' --Add any data here (different from the one searched) to get the position of the last character DECLARE @stringLength BIGINT = len(@string) SELECT pos = Number - LEN(@termToFind) FROM ( SELECT Number , Item = LTRIM(RTRIM(SUBSTRING(@string, Number, CHARINDEX(@termToFind, @string + @termToFind, Number) - Number))) FROM ( --All numbers between 1 and the lengh of @string.

  • do you need data(string) counter of your document??
  • To capture more u'll need to move on to regex. See preg_match_all
  • I looked at preg_match_all, but I can not figure out how to make a regex.
  • Rajib - I do not know what you mean? I want the function to return an array of the occurrences.
  • What do you want the function to do if the data looks like STARTfooSTARTbarENDbazEND?
  • Thank you so much! Just what I wanted!
  • You saved my life, mate! Or at least lots of hours of testing and re-testing xP Thank you soooo much! :)
  • Can someone explain to me what searching algorithm was used to implement this? And can someone explain to me in words what this function precisely does?
  • this is good for standard strings but bad for things like using dollar signs and carrots as delimiters because it messes up regex