John Davidson

php - preg_split with array delimiters with comma not split the array

0 comments
Message:


I have an array with a list in an array and I have to split to find next a value


$artista_inserito = 'DEN HARROW';
$tutti_artisti_data_ora = [
['time_artisti' => '18:31:00', 'artista_artisti' => 'LUIS RODRIGUEZ & DEN HARROW', 'data_artisti' => '2020-04-09'],
['time_artisti' => '18:32:00', 'artista_artisti' => 'J BALVIN', 'data_artisti' => '2020-04-09'],
['time_artisti' => '18:33:00', 'artista_artisti' => 'THE BLACK EYED PEAS VS. J BALVIN', 'data_artisti' => '2020-04-08'],
['time_artisti' => '18:34:00', 'artista_artisti' => 'THE BLACK EYED PEAS FT J BALVIN', 'data_artisti' => '2020-04-09'],
['time_artisti' => '18:35:00', 'artista_artisti' => 'J BALVIN, DEN HARROW', 'data_artisti' => '2020-04-09'],
];
//here a list of delimiter
$databaseDelimiters = array('FEAT', 'feat', 'FT', 'ft', '+', 'AND', 'and', 'E', 'e', 'VS', 'vs', 'FEAT.', 'feat.', 'FT.', 'ft.', 'VS.', 'vs.', ',', '&', 'X', 'x', ', ', ',');

$artistDelimiters = '~ (?:' . implode('|', array_map(function ($v) {
return preg_quote($v, '~');
}, $databaseDelimiters)) . ') ~';

$artists = array_flip(preg_split($artistDelimiters, $artista_inserito));
$result = [];
$autore_duplicato_stringa = '';
foreach ($tutti_artisti_data_ora as $row) {
foreach (preg_split($artistDelimiters, $row['artista_artisti']) as $artist) {
// print the output with every artist
echo $artist . '<br>';
}
}

at now the output is $artista_artisti split by delimiters


LUIS RODRIGUEZ
DEN HARROW
J BALVIN
THE BLACK EYED PEAS
J BALVIN
THE BLACK EYED PEAS
J BALVIN
J BALVIN, DEN HARROW

what's wrong?
the last row must be


J BALVIN
DEN HARROW

why the comma is not recognized?
thanks



My Answer:
The issue is with the way you are defining the artistDelimiters array. You are using a comma as one of the delimiters, but you are not accounting for spaces after the comma.

To fix this, you can update the artistDelimiters array to include the comma with optional spaces after it. Here's the updated code:

php
$artistDelimiters = '~ (?:' . implode('|', array_map(function ($v) {
return preg_quote($v, '~');
}, $databaseDelimiters)) . '|,\\s*) ~';


With this change, the comma followed by optional spaces will be recognized as a delimiter, and the output for the last row will be as expected:


J BALVIN
DEN HARROW


I hope this helps! Let me know if you have any other questions.

Rate this post

3 of 5 based on 7028 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us