How to pick up the strings that are in brackets?

Asked

Viewed 1,873 times

3

Good morning. I appreciate it.. How can I take the contents inside the brackets?

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

It is actually a listing of files that is inside a folder:

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

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

2 answers

4


There are several ways.

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

Use the 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 lines!

You can use the stristr, which has similar function to explode, along with as 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 rule of three 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 exchanged for substr.

  • VLWZÃO HEHEH ;)

  • 1

    I added more alternatives =P

2

You can use the 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 will leave my answer only to have another solution to the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.