如何在不知道PHP长度的情况下获取字符串的第一个整数

时间:2016-04-08 07:23:44

标签: php

如何在不知道确切长度的情况下提取字符串的第一部分(仅整数)?

实施例

123456 - supplier returns 123456
12345 - supplier returns 12345
1234 - supplier returns 1234

5 个答案:

答案 0 :(得分:2)

intval() 非常强大!

echo intval('123456 - supplier');  //123456

这个解释将帮助您理解为什么这样可以正常工作

  

该值由字符串的初始部分给出。如果字符串以有效数字数据开头,则这将是使用的值。否则,该值将为0(零)。有效数字数据是可选符号,后跟一个或多个数字(可选地包含小数点),后跟可选指数。指数是'e'或'E',后跟一个或多个数字。

String Conversion to Numbers

答案 1 :(得分:0)

使用以下代码

$full=explode(' ', '123456 - supplier');
$first=$full[0];

答案 2 :(得分:0)

我们可以通过多种方式实现这一目标

  
      
  1. 常规表达
  2.   
<?php

        $string = '123456 - supplier';
        $pat= '/(\d)*/';

        preg_match_all ($pat, $string, $pat_array);

        $digit  =  $pat_array[0][0];

        echo $digit;
      ?>
  

2.BY ARRAY EXPLODE

<?php
    $string = explode(' ', '123456 - supplier');
    $digit  = $string[0];
 echo $digit;
?>
  
      
  1. INTVAL FUNCTION
  2.   
<?php
$string = '123456 - supplier';

$digit = intval($string);  
echo $digit;
?>

答案 3 :(得分:0)

Preg_match("/(\d+).*/",$string, $number);
Echo $number[1] //returns numbers of string
Echo $number[0] //returns the full string "12345 - supplier"

答案 4 :(得分:0)

Instead of 3 span you need to take only two span like
<div class="col-xs-12 col-sm-12 col-md-3 col-md-offset-2 col-lg-3 col-lg-offset-2 relative">
    <div id="contactinfo" class="text-white">
        <span>client name</span> – 

        <span><a href="mail@something" class="text-green">mail@something</a>-01 23456789</span>
    </div>
</div>

and one changes in css
<style>
  #contactinfo span{display:inline-block;}
 </style>