2010-08-14 5 views
0

문자열이 @로 시작하는 문자열을 필터링하려고합니다. 여기 내가 속임수를 쓸 것이라고 생각했지만 빈 페이지 이상을 돌려주지는 않습니다.특정 패턴이있는 문자열의 시작 부분에있는 숫자 필터링

(내가 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 @."; 
} 
?> 

내 스크립트에 어떤 문제가 있습니까?

미리 감사드립니다.

답변

3
if(substr($String , 0, 1)=="@") 
//      ^^ 2 equal signs for equality comparison. 

BTW 함수는 정규식 (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."; 
} 
관련 문제