Pregunta

Got a number list with separator(s) like these (note: quotes not included):

"1"
"1$^20"
"23$^100$^250"

I watch to write a regex to match both syntax of numbers and separators and also return all numbers in list, the best try I can get in PHP is this code segment:

preg_match_all("/(\d+)(?:\\$\\^){0,1}/", $s2, $n);
print_r($n);

but it returns:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 20
        )

    [1] => Array
        (
            [0] => 1
            [1] => 20
        )

)

What I need is:

Array
(
    [0] => 1
    [1] => 20
)

or at least:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 20
        )
)
¿Fue útil?

Solución

You can just get the first entry in your match array like this:

$s2 = "1$^20";
preg_match_all("/(\d+)(?:\$\^){0,1}/", $s2, $n);
print_r($n[0]);
// Array ( [0] => 1 [1] => 20 )

Or drop the group and just extract the numbers like this:

$s2 = "1$^20";
preg_match_all("/\d+/", $s2, $n);
print_r($n); 
// Array ( [0] => Array ( [0] => 1 [1] => 20 ) )

Another alternative might be to use preg_split:

$s2 = "1$^20";
$n = preg_split('/\$\^/', $s2);
print_r($n);
// Array ( [0] => 1 [1] => 20 )

Otros consejos

I thought about this quesiton again. I know I need not only split them but also check the value syntax. And what if it's a text seprated list? ... Hmm... then a smart way comes into my mind as follows in PHP codes:

// Split and also check value validity of number separated list
$pattern1 = "/(\d+?)\\$\\^/";
$1 = "1^$23";
$s1 .= "$^"; // Always append one separator set
preg_match_all($pattern1, $s1, $matches);

Change \d to . will work for text separated list or number-text-mixed separated list, too.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top