Skip to content

Commit caa2029

Browse files
implement findBetween method to StringHelper
1 parent fcd9e0a commit caa2029

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

framework/helpers/BaseStringHelper.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,4 +527,32 @@ public static function mask($string, $start, $length, $mask = '*') {
527527

528528
return $masked;
529529
}
530+
531+
/**
532+
* Returns the portion of the string that lies between the first occurrence of the start string
533+
* and the last occurrence of the end string after that.
534+
*
535+
* @param string $string The input string.
536+
* @param string $start The string marking the start of the portion to extract.
537+
* @param string $end The string marking the end of the portion to extract.
538+
* @return string The portion of the string between the first occurrence of start and the last occurrence of end.
539+
*/
540+
public static function findBetween($string, $start, $end)
541+
{
542+
$startPos = mb_strpos($string, $start);
543+
544+
if ($startPos === false) {
545+
return '';
546+
}
547+
548+
// Cut the string from the start position
549+
$subString = mb_substr($string, $startPos + mb_strlen($start));
550+
$endPos = mb_strrpos($subString, $end);
551+
552+
if ($endPos === false) {
553+
return '';
554+
}
555+
556+
return mb_substr($subString, 0, $endPos);
557+
}
530558
}

tests/framework/helpers/StringHelperTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,4 +506,30 @@ public function testMask()
506506
$this->assertSame('em**[email protected]', StringHelper::mask('[email protected]', 2, 2));
507507
$this->assertSame('******email.com', StringHelper::mask('[email protected]', 0, 6));
508508
}
509+
510+
/**
511+
* @param string $string
512+
* @param string $start
513+
* @param string $end
514+
* @param string $expectedResult
515+
* @dataProvider dataProviderFindBetween
516+
*/
517+
public function testFindBetween($string, $start, $end, $expectedResult)
518+
{
519+
$this->assertSame($expectedResult, StringHelper::findBetween($string, $start, $end));
520+
}
521+
522+
public function dataProviderFindBetween()
523+
{
524+
return [
525+
['hello world hello', 'hello ', ' world', ''], // end before start
526+
['This is a sample string', 'is ', ' string', 'is a sample'], // normal case
527+
['startendstart', 'start', 'end', ''], // end before start
528+
['startmiddleend', 'start', 'end', 'middle'], // normal case
529+
['startend', 'start', 'end', ''], // end immediately follows start
530+
['multiple start start end end', 'start ', ' end', 'start end'], // multiple starts and ends
531+
['', 'start', 'end', ''], // empty string
532+
['no delimiters here', 'start', 'end', ''], // no start and end
533+
];
534+
}
509535
}

0 commit comments

Comments
 (0)