2

I need help with writing a regular expression in PHP. I am not friend enough to get it right. I need to find all integers in a string and format them as follows:

1 to 001000
0.13 to 000130
100 to 0100000 

and so on. In normal speech it means - edit the number prepend it with zeros or edit it to be in same "order". The point is to have all of the integers it the string in this format (6 numbers). Could someone help me please? I will not post my tryouts here because they are too foolish:-)

3
  • Your last example has 7 digits. Commented Oct 11, 2010 at 8:15
  • 1
    Could there be negative numbers? If so, what should happen with them? Could there be decimal numbers without a leading zero like .13? Commented Oct 11, 2010 at 8:18
  • No to all. There can be only positive values with leading zeros. I get the input from XML file which contains only values as 13 or 20 or 186.578962453. I need to strip the values and make it exactly 6 digits. It will be yoused for searching purposes. Commented Oct 11, 2010 at 8:26

2 Answers 2

2

From your examples looks like you are multiplying the number with 1000 and prefixing them with 0's to make a total of 6 digits. If that is true you can just do:

sprintf("%06d",$n*1000);
Sign up to request clarification or add additional context in comments.

1 Comment

It is not exactly multiplying. I need to have all numbers to have exactly the same lenght. The range is "000.000" to "999.999". And for every number in the input string i need an output which looks like "xxxxxx". Exactly six digits (with prepending zeros) without a point.
1

By using the 'e' modifier on preg_replace() (or using preg_replace_callback()) you can use @codaddict's answer:

function my_format($d) {
    return sprintf('%06d', round($d * 1000));
}

$your_string = '0.12 100 number 1.12 something';

preg_replace('/\d+(\.\d+)?/e', 'my_format(\\0)', $your_string);
// Should give '000120 100000 number 001120 something'

4 Comments

@codaddict Right. I should have copy-pasted your code instead :)
Thanks guys for quick responses. I'll give it a try and let you know:-)
I tryied proposed solution - there should be round($d.... Unless I am guessing something wrong - i need to change ALL of the numeric values including 1.12 in @jengram's example. And also when I tested it - it strips the space after the number. What I need is to let the rest of the string intact. The purpose of this code is to process Zend Lucene query in order to be capable searching float point numbers.... :-) I know I am being...iritating :-D
@Bery Yes, the round() was a(nother) typo. About the 1.12 I misread your comment. I have (hopefully) fixed it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.