Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Capture and edit part of string using regex in PHP

I have to check several strings...the format of each string could be the following:

I-IVWM_Ask-21_(max_2h)

or

D-7849_DG303_(max_4h)

or

Aliante_Privato

I need to capture text in brackets, first part of string outside brackets and replace underscore with spaces.

I'm tring to use preg_match in PHP, as follow

preg_replace('/\([^)]*\)|[()]/', '', $string);

The code above remove string and brackets but leave underscore and doesn't capture the string inside brackets.

Any help to figure out my issue? Thanks

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

What you might do is first match the pattern, and for the match replace the parenthesis and underscores with a space using preg_replace_callback.

Pattern to match the strings:

^[^\s()]+(?:\([^()]*\))?$
  • ^ Start of string
  • [^\s()]+ Match 1+ chars other than parenthesis or whitespace chars
  • (?:\([^()]*\))? Optionally match the part between parenthesis
  • $ End of string

Regex demo | Php demo

For example

$strings = [
    "I-IVWM_Ask-21_(max_2h)",
    "D-7849_DG303_(max_4h)",
    "Aliante_Privato"
];

foreach ($strings as $str) {
    $pattern = "/^[^\s()]+(?:\([^()]*\))?$/";
    echo preg_replace_callback($pattern, function ($x) {
        return trim(preg_replace("/[()_]+/", " ", $x[0]));
    }, $str) . PHP_EOL;
}

Output

I-IVWM Ask-21 max 2h
D-7849 DG303 max 4h
Aliante Privato
over 4 years ago · Santiago Trujillo Relatório

0

$strings = [
    "I-IVWM_Ask-21_(max_2h)",
    "D-7849_DG303_(max_4h)",
    "Aliante_Privato"
];

$result = array_map('trim', preg_filter('~[_()]+~', ' ', $strings));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda