【问题标题】:Filtering out a number at the start of a string which has a certain pattern过滤掉具有特定模式的字符串开头的数字
【发布时间】:2010-08-14 21:17:53
【问题描述】:

如果字符串以@ 开头,我正在尝试从字符串中过滤出一个数字。 这是我认为可以解决问题的方法,但它只返回一个空白页面。

(可能包含很多错误,因为我是 PHP 新手。)

<?php
$String = "@1234 Hello this is a message.";
$StringLength = 1;
Echo "Filtering the number after the @ out of " .$String;
If (substr($String , 0, 1)="@"){ //If string starts with @
    While (is_int(substr($String,1,$StringLength))){ //Check if the X length string after @ is a number.
            $StringLength=$StringLength+1; //If it was a number, up StringLength by one.
    }
    If ($StringLength >= 2){ //If the number is only 1 character long StringLength will be 2, loop completed once.
        $Number = substr($String,1,$StringLength-1);
        Echo $Number;
    }
    Else{ //The string started with @ but the While has never run because it was false.
        Echo "The @ isn't followed by a number.";
    }
Else{ //If string doesn't start with @
    Echo "String doesn't start with @.";
}
?>

我的脚本有什么问题?

提前致谢!

【问题讨论】:

    标签: php string filter numbers


    【解决方案1】:
    if(substr($String , 0, 1)=="@")
    //                       ^^ 2 equal signs for equality comparison.
    

    顺便说一句,您的函数可以简单地用正则表达式 (example) 编写。要获取初始字符,请使用$string[0]

    if (preg_match('/^@(\\d+)/', $string, $results)) {
       echo $results[1];
    } else {
       if ($string[0] != '@')
         echo "String doesn't start with @.";
       else
         echo "The @ isn't followed by a number.";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 2021-09-08
      • 2019-03-20
      • 2022-08-19
      相关资源
      最近更新 更多