【问题标题】:How to select start of a string until a :如何选择字符串的开头直到 a :
【发布时间】:2011-09-06 16:41:01
【问题描述】:

我有这个字符串:

467:some-text-here-1786

如何只选择“:”之前的第一个数值?

谢谢

【问题讨论】:

标签: php


【解决方案1】:

很简单:

list($var) = explode(":",$input);

$tmp = explode(":",$input);
$var = array_shift($tmp);

或(如 PhpMyCoder 所指出的)

$tmp = current(explode(":",$input));

【讨论】:

  • 你也可以用reset()代替array_shift()
  • 您对 array_shift() 的使用将失败,因为它希望参数 1 是一个引用。您需要使用临时变量。
【解决方案2】:
$string = '467:some-text-here-1786';
$var = (int)$string;

既然您要提取一个数字,这就足够了 :) 有关此功能的原因,请查看官方 PHP 手册:http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

它也非常快速且非常安全:您肯定会得到一个号码。

【讨论】:

    【解决方案3】:
    $a = "467:some-text-here-1786";
    $a = explode(":", $a);
    $a = $a[0];
    

    【讨论】:

      【解决方案4】:

      另一种方法:

      $length = strpos($string, ':') + 1;
      $number = substr($string, 0, $length);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-25
        • 2018-01-31
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 2022-08-24
        相关资源
        最近更新 更多