pattern match and extract problem

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi All,
    I expect someone can crack this one in no time.

Ok, what I'd like to do is to match a pattern in a string and extract a  
portion of it. For example if I had a string like:

'The store had apples(20) and pears(30)'

how do I extract the '20' and '30'? ie. if the pattern is 'apples(??)', how  
do I expect  the '??'.

Ta in advance,

Re: pattern match and extract problem

easy enough. you can use a string tokeniser and use the ( as the
delimeter. it depends on how random the string will be to how you will
harvest the number.

for example:

$string = strtok($longstring,'(');

will give you:

20) and pears

then from then you can go...

$num1 = strtok($string,')');

$num1 would be 20.

its basic but would its up to you how you work it you can run
more than one tokeniser at once so tokenise at the ' ' to get each word
or look into a function called explode()

i suppose to say that if the strings will be pretty regular then you
can use this and if not you would have to make it a little more dynamic

hope this helps

Sean Barton

Re: pattern match and extract problem

On Tue, 07 Feb 2006 16:05:32 -0500, David Moore  

Quoted text here. Click to load it

I prefer using the preg functions to extract parts of strings, but that  
requires at least a basic understanding of regular expressions.  At any  
rate, if you want to capture all instances of word(number) you could do  

$matches[0] would be an array of apples(20), pears(30) etc.,
$matches[1] would be an array of all the numbers (20, 30, etc.)

regex match result ->


A Web based regular expressions powered find/replace utility

Re: pattern match and extract problem

Quoted text here. Click to load it

sounds like you only want the numbers.  easy.
preg_match_all("/\((\d\d)\)/", $string, $matches);
or if you want to handle any number of digits,
preg_match_all("/\((\d+)\)/", $string, $matches);

Quoted text here. Click to load it

Site Timeline