Forum Moderators: coopster

Message Too Old, No Replies

extract number from text string

         

scorpion

10:20 pm on Mar 31, 2003 (gmt 0)

10+ Year Member



Anybody know a function that can extract a number from a text string? e.g.

"this is a 5 text string"

a function that can be used to return Integer(5)?

andreasfriedrich

10:30 pm on Mar 31, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Use regular expressions:

Perl [perl.com]


(my $number) = $string =~ m [perldoc.com]!(\d+)!;

PHP [php.net]


preg_match [php.net]('{(\d+)}', $string, $m);
$number = $m[1];

Andreas

jamesa

6:58 am on Apr 1, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey andreas, why the curly braces in the preg_match function? I've seen you do that before but I don't know what that does.

andreasfriedrich

11:26 am on Apr 1, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The syntax for preg_match [php.net] is as follows:

preg_match [php.net](["']pattern["'], $string, $matches);

where the syntax for pattern is as follows:

pattern := delimiter regular_expression delimiter pattern_modifier

/Aaron/i
{Aaron}e
!Aaron!
§Aaron§
'Aaron'

all are valid patterns. Using the slash as a delimiter is not a good idea if you have any slashes in your pattern since those would have to be escaped. To match [domain.tld...] you could use either

/http:\/\/www\.domain\.tld\//

or

!http://www\.domain\.tld/!

The matching engine treats the first character of the pattern as the delimiter. If it has a corresponding character like brackets and braces do then the end delimiter is that corresponding character. Otherwise you simply repeat the delimiter. Everything after the closing delimiter is considered a pattern modifier.

Using curly braces has the advantage that your favorite editor will highlight matching pairs which is quite useful for longer expressions.

Andreas

jamesa

9:57 pm on Apr 1, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



thanks, Andreas! :)