Solved

Regular Expression needed in PHP for matching all but last numbers and comma in a variable

Posted on 2004-10-16
4
200 Views
Last Modified: 2008-02-01
I am working in PHP and using preg_match to try to retrieve the following.

$line = "             Liatris spicata `Floristan Violet' DND 1                     4,111" (yes, there are multiple spaces in there).

Essentially I need to pull out two different variables from this $line: $product, and $quantity, which should be as follows:

$product = "Liatris spicata `Floristan Violet' DND 1" (notice I stripped spaces before and after)
$quantity = "4,111" (I basically want to do a search starting from the last character of the line, moving left until the first SPACE I find, but I DO want to include commas, since this is a quantity variable)

Any help please?  Thanks so much.
0
Comment
Question by:djs120
  • 3
4 Comments
 
LVL 27

Accepted Solution

by:
Diablo84 earned 500 total points
ID: 12329376
You can do this with string functions which will be quicker then regex, eg:

$line = "             Liatris spicata `Floristan Violet' DND 1                     4,111";

$pos = strrpos($line," ");
$quantity = substr($line,$pos+1);
$product = trim(substr($line,0,$pos));
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12329391
To test the output:

echo "Product: [".$product."]<br>\n";
echo "Quantity: [".$quantity."]\n";

Note: i added the square brackets to demonstrate the stripped spaces
0
 
LVL 1

Author Comment

by:djs120
ID: 12329431
Thanks Diablo.  That's exactly what I was looking for and it worked perfectly with my script on all the data I am testing it with.  Thanks for responding so quickly.
0
 
LVL 27

Expert Comment

by:Diablo84
ID: 12329448
no problem :)

|)iablo
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question