Match comma to new line with regex

I have a comma-separated list that I want to import into the database, and in some cases the last item is empty:

item1, item2, item3
item1, item2,
item1, item2,

I would like to replace all these empty columns with a placeholder value using regexp

item1, item2, item3
item1, item2, PLACEHOLDER
item1, item2, PLACEHOLDER

I tried this:

preg_replace("/,\n/", ",PLACEHOLDER\n",$csv);

... but it does not work. Does anyone know which regular expression will work for this?

+3
source share
3 answers

preg_replace("/,\s*$/m", ", PLACEHOLDER\n", $csv);must do it. This pattern matches a comma, followed by any number of spaces, followed by the end of the line, and replaces it with placeholder text.

+3
source
preg_replace("/,$/m", ", PLACEHOLDER", $csv);

$ m. $ - " " , m - .

m (PCRE_MULTILINE)

PCRE subject "" ( ). " " (^) , " " ($) ( D ). , Perl. , " " " " ​​ , , . Perl /m. \n ^ $ , .

0

To avoid inserting blank lines, and also to capture an incomplete list in the last line, the regex should provide an alternative like this:

$csv = preg_replace('/(?:,\s*[\r\n]+)|(?:,\s*$)/', ", PLACEHOLDER\n", $csv);
0
source

Source: https://habr.com/ru/post/1783750/


All Articles