dongliuzhuan1219 2013-06-03 02:57
浏览 32
已采纳

在PHP中强制执行字符串格式

I am taking in a string from a text field and then sending it to a mysql database with the help of php, using just one variable called '$location'.

I am taking in a "City, State" from the text field.

My question is, is there anyway to enforce the format to be "city[space]comma[space]state"? There must be a comma between the city and the state but spaces are not necessary but a user may put spaces if they feel like and state can only be two letters long.

Also a city name can have a space in it. I.e., "Myrtle Creek, OR"

Thanks.

  • 写回答

1条回答 默认 最新

  • dprh34164 2013-06-03 02:59
    关注

    It's possible with a bit of regex:

    if (preg_match('/^[\w\s]+\s*?,\s*?[a-z]{2}$/i', $location)) {
      // it has city, one comma and two-letter state
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源