Skip to content

Instantly share code, notes, and snippets.

@bennettblack
Created March 18, 2022 19:53
Show Gist options
  • Save bennettblack/3874070281d72d675a03f09c2450c77d to your computer and use it in GitHub Desktop.
Save bennettblack/3874070281d72d675a03f09c2450c77d to your computer and use it in GitHub Desktop.
String Service
<?php
namespace App\Services;
class StringService
{
/**
* Find ALL strings that are between two strings. Optionally include delimiters.
*/
function strBetweenAll(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
$strings = [];
$length = strlen($string);
while ($offset < $length)
{
$found = $this->strBetween($string, $start, $end, $includeDelimiters, $offset);
if ($found === null) break;
$strings[] = $found;
$offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
}
return $strings;
}
/**
* Find a string between two strings. Optionally include delimiters.
*/
function strBetween(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
if ($string === '' || $start === '' || $end === '') return null;
$startLength = strlen($start);
$endLength = strlen($end);
$startPos = strpos($string, $start, $offset);
if ($startPos === false) return null;
$endPos = strpos($string, $end, $startPos + $startLength);
if ($endPos === false) return null;
$length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
if (!$length) return '';
$offset = $startPos + ($includeDelimiters ? 0 : $startLength);
$result = substr($string, $offset, $length);
return ($result !== false ? $result : null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment