Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extracting numbers from a string

Status
Not open for further replies.

MrBelfry

IS-IT--Management
May 21, 2003
289
Hey everybody

litle help?

I have some strings that may look like this:

12vikki.html or 1002richie.html or 1terry.html

I would like to know how I go about parsing the string and place the numbers in another variable.

Any help or pointers will be appreciated

Thanks

MrBelfry
 
regex would be the best way...otherwise look at the using string length to create a loop to move thru the string chr by chr and passing each to an array until you hit a alph chr

hth


Bastien

Cat, the other other white meat
 
If the number-parts will always appear at the beginning of the filenames, you don't need to use regular expressions. Just typecast the variable to an integer -- PHP will stop converting the string to a number when it reaches the first non-numeric character. The script:

Code:
<?php
$a = '12vikki.html';
$b = (int) $a;
print $b;
?>

returns "12" on my LAMP machine.

Likewise, you can strip floating-point numbers. This script:

Code:
<?php
$a = '12.25vikki.html';
$b = (float) $a;
print $b;
?>

Returns "12.25" on my LAMP box.

Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top