How do I get the strings that are enclosed in brackets?

3

Good morning. Thank you very much in advance.. How can I get the content inside the brackets?

lang[en-US].php
lang[pt-BR].php

In fact it is a list of files that are inside a folder:

$atual = $ap . $dir . '/' . $file;
if(is_file($atual)) {
   echo '<li>'.$file.'</li>';
}

But I want $file , which corresponds to ex: lang[pt-BR].php , print only what is between the brackets. EX: pt-BR

    
asked by anonymous 02.04.2016 / 15:24

2 answers

4

There are several ways.

What I would prefer, for being more practical (= P):

Use explode , which breaks the string where it determines.

<?php

$texto = 'lang[en-US].php';
// Seu $texto

$texto = explode('[', $texto);
// $texto agora possui: [0] => 'lang', [1] => en-US].php

$texto = explode(']', $texto[1]);
// $texto agora possui [0] => en-US, [1] => .php

echo $texto[0];
// Resultado: en-US

STRISTR: I want something with fewer rows!

You can use stristr , which has a function similar to explode , together with str_replace .

$texto = 'lang[en-US].php';
$cortado = stristr(stristr($texto, '['), ']', true);

// Escolha um para remover os [:
$texto = str_replace('[', '', $cortado);
// OU
$texto = substr($cortado, 1);

REGEX: I want to use REGEX

Because REGEX is the three rule of programming.

$texto = 'lang[en-US].php';
preg_match('/\[(.*?)\]/', $texto, $cortado);

// Escolha um para remover os []:
$texto = str_replace('[', '', str_replace(']', '', $cortado[0]));
// OU
$texto = substr($cortado[0], 1, -1); 
//OU
$texto = $cortado[1];

Note:

  

The str_replace can be changed by substr .

    
02.04.2016 / 15:57
2

You can use preg_match () :

PHP

$atual = $ap . $dir . '/' . $file;
preg_match('/\[(.*)\]/', $file, $matches);
if(is_file($atual)) {
    echo '<li>' . $matches[1] . '</li>';
}

Explanation of regular expression

\[ encontra o caracter [ literalmente
    Primeiro grupo a ser capturado (.*)
        .* encontra qualquer caracter (exceto quebra de linha)
            Quantificador: * Entre zero à ilimitadas vezes
\] encontra o caracter [ literalmente

DEMO

- EDIT -

As @Inkeliz pointed out, there are several ways to get the solution. Personally, I would also use the @Inkeliz solution:)

I'll leave my answer just to have another solution to the problem.

    
02.04.2016 / 15:57