NEW dolExplodeIntoArray can accept regex

This commit is contained in:
Laurent Destailleur
2023-04-07 16:21:51 +02:00
parent c1cbf1805a
commit 3b8406a83e
2 changed files with 17 additions and 2 deletions

View File

@@ -9805,13 +9805,21 @@ function printCommonFooter($zone = 'private')
* For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3) * For example: "A=1;B=2;C=2" is exploded into array('A'=>1,'B'=>2,'C'=>3)
* *
* @param string $string String to explode * @param string $string String to explode
* @param string $delimiter Delimiter between each couple of data * @param string $delimiter Delimiter between each couple of data. Example: ';' or '[\n;]+' or '(\n\r|\r|\n|;)'
* @param string $kv Delimiter between key and value * @param string $kv Delimiter between key and value
* @return array Array of data exploded * @return array Array of data exploded
*/ */
function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=') function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
{ {
if ($a = explode($delimiter, $string)) { if (preg_match('/^\[.*\]$/sm', $delimiter) || preg_match('/^\(.*\)$/sm', $delimiter)) {
// This is a regex string
$newdelimiter = $delimiter;
} else {
// This is a simple string
$newdelimiter = preg_quote($delimiter, '/');
}
if ($a = preg_split('/'.$newdelimiter.'/', $string)) {
$ka = array(); $ka = array();
foreach ($a as $s) { // each part foreach ($a as $s) { // each part
if ($s) { if ($s) {
@@ -9824,6 +9832,7 @@ function dolExplodeIntoArray($string, $delimiter = ';', $kv = '=')
} }
return $ka; return $ka;
} }
return array(); return array();
} }

View File

@@ -1381,6 +1381,12 @@ class FunctionsLibTest extends PHPUnit\Framework\TestCase
print __METHOD__." tmp=".json_encode($tmp)."\n"; print __METHOD__." tmp=".json_encode($tmp)."\n";
$this->assertEquals('{"AA":"B\/B","CC":"","EE":"FF","HH":"GG;"}', json_encode($tmp)); $this->assertEquals('{"AA":"B\/B","CC":"","EE":"FF","HH":"GG;"}', json_encode($tmp));
$stringtoexplode="AA=B/B;CC=\n\rEE=FF\nHH=GG;;;\nII=JJ\n";
$tmp=dolExplodeIntoArray($stringtoexplode, "(\r\n|\n|\r|;)", '=');
print __METHOD__." tmp=".json_encode($tmp)."\n";
$this->assertEquals('{"AA":"B\/B","CC":"","EE":"FF","HH":"GG","II":"JJ"}', json_encode($tmp));
} }
/** /**