2012-03-09 16:52
浏览 51


Updating someone else's old PHP project and I'm unfamiliar with regular expressions.

Question one is: What does this do?

preg_match('/^[0-9]+[.]?[0-9]*$/', $variable)

Question two is: Is this a safe filter for insertion into a mysql DB without mysql_real_escape_string()? I know the answer is prob no, but it is set up to use mysql_real_escape_string() only if this regex doesn't pass.


  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

7条回答 默认 最新

  • dthswrp84966
    dthswrp84966 2012-03-09 16:57
    ^      // start of string
    [0-9]+ // one or more numbers (could also be \d+)
    [.]?   // zero or one period (could also be \.?)
    [0-9]* // zero or more numbers (could also be \d*)
    $      //end of string

    So, it makes sure the input is a number, such as 12 or 3.6 (52. will also match). It will not match .35 or 12a6.

    It seems safe enough for DB insertion, because it only allows numbers.

    点赞 评论
  • duanfen1312
    duanfen1312 2012-03-09 16:55

    It's attempting to match a decimal number (albeit poorly). It doesn't modify $variable anyway, so you would need to escape it properly before passing to MySQL.

    点赞 评论
  • doupiao1893
    doupiao1893 2012-03-09 16:55

    That will match a number that has at least one digit before the decimal point (if there is a decimal point). If the value matches this regex, I don't see how it could be unsafe to insert it into the database.

    点赞 评论
  • douxiegan6468
    douxiegan6468 2012-03-09 16:56

    looks if the a exact match. it matches 234234232432343.231313132321 and 2232233223 and 322332. and not .32232 and not

    点赞 评论
  • du6333137
    du6333137 2012-03-09 16:56

    it matches strings that:

    1. start with at least 1 digit from 0-9
    2. have a decimal point after the first n digits 0 or 1 time
    3. have any digit after a char 0 or more times
    点赞 评论
  • dpzff20644
    dpzff20644 2012-03-09 16:57

    It does not sanitise string for database.

    It checks if $variable matches this pattern...

    1. starts with one or more digits (^[0-9]+)
    2. followed by optional . ([.]?)
    3. followed by as many or as few digits as you like ([0-9]*)
    4. followed by the end of the string ($)
    点赞 评论
  • dou9022
    dou9022 2012-03-09 17:00

    Is this a safe filter for insertion into a mysql DB without mysql_real_escape_string()?

    Assuming the possible use of this variable, I'd say that mysql_real_escape_string() would be quite useless for it.
    Need the query assembling code to be certain though.

    点赞 评论