开发者

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜