Created
March 18, 2022 19:53
-
-
Save bennettblack/3874070281d72d675a03f09c2450c77d to your computer and use it in GitHub Desktop.
String Service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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