Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numeric range from text string function 1

Status
Not open for further replies.

Mthales

Technical User
Feb 27, 2004
1,181
GB
Hi,
I am trying to implement a php script that takes in a piece of text from users and interprets it to be a numeric range.
Examples of what I would consider valid entries would be "1-6" or "6+9+14" or "1-4,12" or "12".

This seems to me to be something that happens quite a lot in all sorts of situations so I was expecting to be able to find an example that could show me a sensible way to achieve this but I have searched high and low and can't find anything.

Can any of you point me in the right direction?
Thanks


M [wiggle]
 
---------your post---------
Examples of what I would consider valid entries would be "1-6" or "6+9+14" or "1-4,12" or "12".
---------your post---------

Can you explain in detail about the ranges? What you trying to achieve here? One intrepretation of the valid entries could be

"1-6" --> 1 to 6 or ???
"6+9+14" --> max 29 or ???
"1-4,12" --> 5 to 12 or ???
"12" --> max value is 12 or ???

Information is not knowledge.
 
I guess like a document:

1-6: lines 1 to 6 (or pages)
1-4,12: lines 1 to 4 and line 12
12: line 12

but 6+9+14... I can't get it...

Chacal, Inc.
 
Charcalinc is correct that is what I intended those examples to mean and "6+9+14" is meant to be 6 and 9 and also 14.

M [wiggle]
 
I'll work under the assumption that "6,9,14" and "6+9+14" mean the same thing.

Try this:

Code:
<?php

function ranger ($string)
{
	$retval = array();

	//since "+" and "," mean the same thing, convert one to the other.
	$string = str_replace ('+', ',', $string);

	$elements = explode (',', $string);
	
	foreach ($elements as $element)
	{
		if (strstr($element, '-') !== FALSE)
		{
			//element is something of the form 'number dash number'
			$parts = explode ('-', $element);
			for ($counter = $parts[0]; $counter <= $parts[1]; $counter++)
			{
				$retval[] = $counter;
			}
		}
		else
		{
			//Singleton number
			$retval[] = $element;
		}
	}

	return $retval;
}


print '<html><body><pre>';
$b = ranger('1-4,12');
print_r ($b);

$b = ranger ('12');
print_r ($b);


$b = ranger ('6+9+14');
print_r ($b);
print '</pre></body></html>';

?>


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Thank you very much sleipnir214 that is absolutly what I wanted to do. I appreciate your help.

M [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top