php ctype_digit没有告诉字符串是否为数字

时间:2017-06-08 09:52:33

标签: php

我有一个脚本,我想用它来处理来自客户端的用户输入。我有几个检查,但第一个检查要求提交的字符串是数字。

这是代码

<?php
$num = '09201x11222';

//Check whether the string is numeric
function test($str){
  return ctype_digit($str);
}

echo test($num);

echo '<br/><br/><br/>';

//Check if the length is exactly 10 characters
$len = strlen($num);
if($len < 10 || $len > 10){
  echo 'that number is wrong';
}
elseif($len == 10){
  echo 'that number is of required length';
}
echo '<br/><br/><br/>';
//Trim Leading Zero
$afterTrim = substr($num,1);

echo $afterTrim;

//Append countrycode 380 
echo '<br/><br/><br/>';

$countryCode = '380';
$afterAppend = $countryCode.$afterTrim;

echo $afterAppend;

?>

$num正确时,我在屏幕上得到1但是当它出错时我什么也得不到。那是为什么?

1 个答案:

答案 0 :(得分:0)

回应 <% @quote = local_assigns[:quote] %> <%= link_to quote_path(@quote) do %> <section id="quotes"> <!-- <div class="container"> --> <div class="col-md-4 col-md-4 col-md-4 text-center"> <div class="panel panel-success panel-quote link-panel"> <div class="panel-heading"> <strong>GLA</strong> </div> <div class="panel-body"> <p><strong>Quote ID; <%= @quote.id %></strong></p> </div> <table class="table table-bordered"> <tr> <td>Company name</td> <td><%= @quote.co_name %></td> </tr> <tr> <td>Company number</td> <td><%= @quote.co_number %></td> </tr> <tr> <td>Office postcode</td> <td><%= @quote.postcode %></td> </tr> <tr> <td>Industry</td> <td><%= @quote.industry %></td> </tr> <tr> <td>Previous cover</td> <td><%= @quote.prev_cover %></td> </tr> <tr> <td>Lives overseas</td> <td><%= @quote.lives_overseas %></td> </tr> <tr> <td>Scheme start date</td> <td><%= @quote.scheme_start_date %></td> </tr> <tr> <td>Payment frequency</td> <td><%= @quote.payment_frequency %></td> </tr> <tr> <td>Commission level</td> <td><%= @quote.commission_level %></td> </tr> </table> </div> </div> <!-- </div> --> </section> </div> <% end %> 将导致“无效”打印。这是因为false需要将一个布尔值转换为字符串表示。

从方法签名

可以看出
echo

这将返回一个由echo转换的布尔值:如果bool ctype_digit ( string $text ) ,它将打印true,否则它将不打印任何内容。

来自manual

  

布尔值TRUE值转换为字符串“1”。 Boolean FALSE转换为“”(空字符串)。这允许在布尔值和字符串值之间来回转换。

相关问题