Regular expression to only allow whole numbers and commas in a string

后端 未结 4 1209
心在旅途
心在旅途 2020-12-19 16:19

Does anyone know what the preg_replace would be for a string to only allow whole numbers and commas? I want to strip all whitespace, letters, symbols, etc, so all that is le

4条回答
  •  情书的邮戳
    2020-12-19 17:03

    This should do what you need:

    $str = preg_replace(
      array(
        '/[^\d,]/',    // Matches anything that's not a comma or number.
        '/(?<=,),+/',  // Matches consecutive commas.
        '/^,+/',       // Matches leading commas.
        '/,+$/'        // Matches trailing commas.
      ),
      '',              // Remove all matched substrings.
      $str
    );
    

提交回复
热议问题