Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!