-1

Is there a way in PHP, that you can convert the following regular expression

3.[0123]

To

3.0, 3.1, 3.2, 3.3

Thank you for looking in to this :)

EDIT: Sorry i was unclear :/ I want to read out XML, and show that on a web-page, and i want to show that to users. In that XML, there is a regular expression like this one:

3.[0123]

My question is: Can I convert a regular expression like the one above me, to a readeble text that the average user understands :)

So that the user sees this: 3.1, 3.2, 3.3, ...

And not this: 3.[0123] (this is an example, it can be every number).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Rob
  • 123
  • 6

3 Answers3

0

Something like this?

$start= "3.[0123]";
$value = explode("[", $start);
$sequences = str_split($value[1]);
array_pop($sequences);
foreach ($sequences as $sequence) {
    $array[] = $value[0].$sequence;
}
var_dump($array);
codable
  • 11
  • 4
0

You can use the or to make the regex a bit more readable.

(3\.0|3\.1|3\.2|3\.3)

Also note the escaping of .. The . is a special character in regex and means "any character" your regex as is would have allowed more than just 3.0, 3.1, 3.2, or 3.3. You also should use anchors to ensure that is the only value in the string. So a final version (without delimiters):

^(3\.0|3\.1|3\.2|3\.3)$
chris85
  • 23,846
  • 7
  • 34
  • 51
0

If I understand you correctly, you're looking to expand a regular expression into all possibilities, i.e. a list of all results that would satisfy it. The general case for this is a seriously complex problem, and would regularly result in an infinite number of possibilties (where .+ is used, for example). See Regular expression listing all possibilities for a bit more discussion of that.

For a simple case though, where there is a single character class, it's easy enough to expand out the possibilities,

<?php
$base = '3.[0123]';

// Match a single character class, e.g. [0123] or [ABC]
$matches = [];
preg_match('/\[(\w+)\]/', $base, $matches);

list($expansion, $options) = $matches;

$possibilities = [];

// For each possible character in the class, replace the full original
// character class in the expression with that character
foreach (str_split($options) as $option)
{
    $possibilities[] = str_replace($expansion, $option, $base);
}

print_r($possibilities);

=

Array
(
    [0] => 3.0
    [1] => 3.1
    [2] => 3.2
    [3] => 3.3
)
Community
  • 1
  • 1
iainn
  • 16,826
  • 9
  • 33
  • 40