当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Match a comma followed by a newline with a regular expression

问题描述:

I have a comma delimited list I want to import into a database, and in some cases the last item is blank:

item1, item2, item3

item1, item2,

item1, item2,

I'd like to replace all of these empty columns with a placeholder value using a regexp

item1, item2, item3

item1, item2, PLACEHOLDER

item1, item2, PLACEHOLDER

I tried this:

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

...but it isn't working. Anyone know what regexp would work for this?

网友答案:

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

网友答案:
preg_replace("/,$/m", ", PLACEHOLDER", $csv);

Use $ along with the m modifier. $ is the "end of line" anchor and m enables multiline mode.

m (PCRE_MULTILINE)

By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless D modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no \n characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect.

网友答案:

In order to avoid inserting blank lines, as well as capturing an incomplete list on the final line, the regex needs to provide an alternative like this:

$csv = preg_replace('/(?:,\s*[\r\n]+)|(?:,\s*$)/', ", PLACEHOLDER\n", $csv);
分享给朋友:
您可能感兴趣的文章:
随机阅读: