Solved

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

Posted on 2004-10-16
4
196 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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article discusses four methods for overlaying images in a container on a web page
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

708 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now