Merge pull request #28803 from mdeweerd/fix/get_string_between

FIX get_string_between
This commit is contained in:
Laurent Destailleur 2024-03-13 10:54:25 +01:00 committed by GitHub
commit 7400a1b879
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 52 additions and 8 deletions

View file

@ -1431,23 +1431,28 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $
}
/**
* Get string between
* Get string from "$start" up to "$end"
*
* If string is "STARTcontentEND" and $start is "START" and $end is "END",
* then this function returns "content"
*
* @param string $string String to test
* @param int $start Value for start
* @param int $end Value for end
* @param string $start String Value for start
* @param string $end String Value for end
* @return string Return part of string
*/
function get_string_between($string, $start, $end)
{
$string = " ".$string;
$ini = strpos($string, $start);
if ($ini == 0) {
return "";
if ($ini === false) {
return '';
}
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
$endpos = strpos($string, $end, $ini);
if ($endpos === false) {
return '';
}
return substr($string, $ini, $endpos - $ini);
}
/**

View file

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2010-2012 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2023 Alexandre Janniaux <alexandre.janniaux@gmail.com>
* Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -205,4 +206,42 @@ class Functions2LibTest extends CommonClassTest
print __METHOD__." for ".$ip." result=".$result."\n";
$this->assertEquals(2, $result, $ip);
}
/**
* Dataprovider for testGetStringBetween
*
* @return array<string,string[]}
*/
public function stringBetweenDataProvider()
{
return [
// string, start, end, expected
'matches' => [ "STARTcontentEND", "START", "END", "content"],
'start does not match' => [ "ScontentEND", "START", "END", ""],
'end does not match' => [ "STARTcontentN", "START", "END", ""],
'no match' => [ "content", "START", "END", ""],
'end before start' => [ "ENDcontentSTART", "START", "END", ""],
'end inside start' => [ "BAB", "BA", "AB", ""],
'multiple matches' => [ "BAcontentABBAdoneAB", "BA", "AB", "content"],
];
}
/**
* Test get_string_between()
*
* @param string $string String to search in.
* @param string $start String indicating start
* @param string $end String indicating end
* @param string $expected Expected result
*
* @return void
*
* @dataProvider stringBetweenDataProvider
*/
public function testGetStringBetween($string, $start, $end, $expected)
{
$this->assertEquals($expected, get_string_between($string, $start, $end));
}
}