2010-08-14 4 views
0

J'essaie de filtrer un nombre d'une chaîne si cette chaîne commence par @. Voici ce que je pensais faire l'affaire, mais il ne retourne rien de plus qu'une page blanche.Filtrer un nombre au début d'une chaîne qui a un certain motif

(Peut contenir beaucoup d'erreurs que je suis nouveau à 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 @."; 
} 
?> 

Quel est le problème avec mon script?

Merci d'avance!

Répondre

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

BTW votre fonction peut être écrit simplement avec regex (example). Et pour obtenir le caractère initial, utilisez $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."; 
} 
Questions connexes