如何在第一个非数字字符之前打印所有内容

时间:2019-01-22 03:16:52

标签: php

我想知道如何打印字符串,但是一旦看到非数字字符,我就会停止。例如:

$input1 = "1111n93";
// Output should be "1111"

$input2 = "df22222";
// Output should be blank

$input3 = "39393939dfg2222222"
// Output should be 39393939

我最初的解决方法是(但这仅检查字符a)。如何对所有非数字字符执行此操作。我想拥有最有效的方法。

$string = "123456a99";
echo strtok($mystring, 'a');

3 个答案:

答案 0 :(得分:1)

这将为您工作:

preg_match("/^[0-9]+/", $mystring, $digit_prefix);
echo $digit_prefix[0] ; // this might be empty if no digits found

答案 1 :(得分:0)

在这种罕见的情况下,PHP的疯狂输入非常有用:

$input1 = "1111n93";
$input2 = "df22222";
$input3 = "39393939dfg2222222";

echo (int)$input1;
echo (int)$input2;
echo (int)$input3;

输出:

1111
0
39393939

答案 2 :(得分:0)

两种方式: 1.像miken32一样将其转换为int 2.对任何类型的数字使用提示:

<form id='calc'>
  <fieldset>
    <legend>Calculation 1</legend>
    <input class="A" type="number" value="0" min='-9999.99' max="9999.99" step='.01'>
    <select class='O'>
      <option value='-'>&minus;</option>
      <option value='+'>&plus;</option>
      <option value='*'>&times;</option>
      <option value='/'>&divide;</option>
    </select>
    <input class="B" type="number" value="0" min='-9999.99' max="9999.99" step='.01'><label>&nbsp;=&nbsp;</label>
    <output class='C'></output>
  </fieldset>

  <fieldset>
    <legend>Calculation 2</legend>
    <input class="A" type="number" value="0" min='-9999.99' max="9999.99" step='.01'>
    <select class='O'>
      <option value='-'>&minus;</option>
      <option value='+'>&plus;</option>
      <option value='*'>&times;</option>
      <option value='/'>&divide;</option>
    </select>
    <input class="B" type="number" value="0" min='-9999.99' max="9999.99" step='.01'><label>&nbsp;=&nbsp;</label>
    <output class='C'></output>
  </fieldset>

  <fieldset>
    <legend>Calculation 3</legend>
    <input class="A" type="number" value="0" min='-9999.99' max="9999.99" step='.01'>
    <select class='O'>
      <option value='-'>&minus;</option>
      <option value='+'>&plus;</option>
      <option value='*'>&times;</option>
      <option value='/'>&divide;</option>
    </select>
    <input class="B" type="number" value="0" min='-9999.99' max="9999.99" step='.01'><label>&nbsp;=&nbsp;</label>
    <output class='C'></output>
  </fieldset>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>