Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

213
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda