1

Today i came across this problem, how to split out / differentiate is str and is int from a random input? Example, my user can input as below:-

  1. A1 > str:A, int:1
  2. AB1 > str:AB, int:1
  3. ABC > str:ABC, int:1
  4. A12 > str:A, int:12
  5. A123 > str:A, int:123

my current script is using substr(input,0,1) to get str and substr(input,-1) to get int, but it will give error if having input for case 2,3,4,5 or any others style of user input

Thanks

3
  • Just use some pregmatch function to find some number (0-9 ^^) Commented May 29, 2013 at 15:17
  • 1
    This has already been answered by the looks of it: [stackoverflow][1] [1]: stackoverflow.com/questions/5474088/… Commented May 29, 2013 at 15:19
  • @jimmy - dunno if you misposted the link, but that's nothing like the same question Commented May 29, 2013 at 15:24

4 Answers 4

8
list($string, $integer) = sscanf($initialString, '%[A-Z]%d');
Sign up to request clarification or add additional context in comments.

Comments

5

Use a regular expression like the following.

// $input contains the input
if (preg_match("/^([a-zA-Z]+)?([0-9]+)?$/", $input, $hits))
{
    // $input had the pattern we were looking for
    // $hits[1] is the letters
    // $hits[2] holds the numbers
}

The expression will look for the following

^               start of line
([a-zA-Z]+)?    any letter upper or lowercase
([0-9]+)?       any number
$               end of line

(..+)? in this the + means "one or more" while the ? means 0 or 1 times. So you are looking for sth that is whatever long and appears or doesn't

Comments

1

I recommend you use a regex to identify and match String and number part: Something like

if (!preg_match("/^.*?(\w?).*?([1-9][0-9]*).*$/", $postfield, $parts)) $parts=array();
if (sizeof($parts)==2) {
    //$parts[0] has string
    //$parts[1] has number
}

will silently ignore invlid parts. You do still need to validate length and range of the parts.

Comments

1

How about this? regular expressions

$str = 'ABC12';
preg_match('/[a-z]+/i', $str, $matches1);
preg_match('/[0-9]+/', $str, $matches2);

print_r($matches1);
print_r($matches2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.