Domanda

i want to preg_match following as it is

$this_string = '{95}1340{113}1488{116}1545{99}1364';

My best try was

preg_match('/^[\{\d+\}\d+]+$/', $this_string);

That matches

{95}1340{113}1488 

but also

{95}1340{113}

which is wrong. I know why it is matching last example. One match {95}1340 was true, so '+' 'll be always true. But i don't know how to tell, if it match, so it has always be a complete match in '[…]'

i do expect only matches likes these

{…}…
{…}…{…}…
{…}…{…}…{…}…

one of the tries:

^(\{\d+\}\d+)+$

does also match

{99}1364

at the very last end of this string as a second match, so i get back an Array with two Elements:

Array[0] = {95}1340{113}1488{116}1545{99}1364 and
Array[1] = {99}1364
È stato utile?

Soluzione

Problem is unnecessary use of character class in your regex i.e. [ and ].

You can use:

'/^(\{\d+\}\d+)+$/'

Altri suggerimenti

The translation of your regex to a clearer thing would be: /^[\{\}0-9+]+$/, this would be explained as everything that is inside this chracters {}0123456789+, exactly those ones.

What you want is grouping, for grouping, parentheses are needed and not character classes () instead [], so what you want to do is replace [] for ().

Short answer: '/^(\{\d+\}\d+)+$/'

What you are trying to do is a little unclear. Since your last edit, I assume that you want to check the global format of the string and to extract all items (i.e. {121}1231) one by one. To do that you can use this code:

$str = '{95}1340{113}1488{116}1545{99}1364';
$pattern = '~\G(?:{\d+}\d+|\z)~';
if (preg_match_all($pattern, $str, $matches) && empty(array_pop($matches[0])))
    print_r($matches[0]);

\G is an anchor for the start of the string or the end of the previous match
\z is an anchor for the end of the string

The alternation with \z is only needed to check that the last match is at the end of the string. If the last match is empty, you are sure that the format is correct until the end.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top