开发者

Problem using regex to remove number formatting in PHP

I'm having this issue with a regular express开发者_如何学Cion in PHP that I can't seem to crack. I've spent hours searching to find out how to get it to work, but nothing seems to have the desired effect.

I have a file that contains lines similar to the one below:

Total','"127','004"','"118','116"','"129','754"','"126','184"','"129','778"','"128','341"','"127','477"','0','0','0','0','0','0

These lines are inserted into INSERT queries. The problem is that values like "127','004" are actually supposed to be 127,004, or without any formatting: 127004. The latter is the actual value I need to insert into the database table, so I figured I'd use preg_replace() to detect values like "127','004" and replace them with 127004.

I played around with a Regular Expression designer and found that I could use the following to get my desired results:

Regular Expression

"(\d+)','(\d{3})"

Replace Expression

$1$2

The line on the top of this post would end up like this: (which is what I am after)

Total','127004','118116','129754','126184','129778','128341','127477','0','0','0','0','0','0

This, however, does not work in PHP. Nothing is being replaced at all.

The code I am using is:

$line = preg_replace("\"(\d+)','(\d{3})\"", '$1$2', $line);

Any help would be greatly appreciated!


There are no delimiters in your regex. Delimiters are required in order for PHP to know what is the pattern to match and what is a pattern modifier (e.g. i - case-insensitive, U - ungreedy, ...). Use a character that doesn't occur in your pattern, typically you'll see a slash '/' used.

Try this:

$line = preg_replace("/\"(\d+)','(\d{3})\"/", '$1$2', $line);


You forgot to wrap your regular expression in front-slashes. Try this instead:

"/\"(\d+)','(\d{3})\"/"


use preg_replace("#\"(\d+)','(\d+)\"#", '$1$2', $s); instead of yours

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜