Domanda

text text text
text text text

{test}
    content
    content
    content
{/test}

text text text
text text text

ho bisogno di ottenere due risultati separati dalla stringa di cui sopra:
1.

{test}
    content
    content
    content
{/test}

2.

    content
    content
    content

così, quali dovrebbero essere i due separati modelli di espressioni regolari per PHP per ottenere questi due risultati

È stato utile?

Soluzione

Che dire qualcosa di simile:

$str = <<<STR
text text text
text text text

{test}
    content
    content
    content
{/test}

text text text
text text text
STR;

$m = array();
if (preg_match('#\{([a-zA-Z]+)\}(.*?)\{/\1\}#ism', $str, $m)) {
    var_dump($m);
}

Quale sarà possibile ottenere questo tipo di output:

array
  0 => string '{test}
    content
    content
    content
{/test}' (length=50)
  1 => string 'test' (length=4)
  2 => string '
    content
    content
    content
' (length=37)

Quindi, in $m[0] avete tutto il testo trovato (vale a dire i tag + contenuti) , e in $m[2] basta contenuti tra i tag.

Si noti che ho usato i tag "generici", e non specificamente "test"; si può cambiare che se avrete solo tag "test".

Per ulteriori informazioni, è possibile dare un'occhiata a, almeno:

Altri suggerimenti

Per catturare i tag e contenuti insieme:

/(\{test\}[^\x00]*?\{\/test\})/

Per catturare solo il contenuto:

/\{test\}([^\x00]*?)\{\/test\}/
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top