Question

currently i am using php preg_replace to replace certain portion of string

12854827.12854827_IDS.0 12854827.12854827_892.0
12854827.12854827_IDS.0 12854827.12854827_892.0

here i required output is

12854827.IDS.0 12854827.892.0
12854827.IDS.0 12854827.892.0

but preg_replace produced output

12854827.892.0
12854827.892.0

php code that i used given below

preg_replace('/\..*_/', '.', $A)

how i solve above problem ? & how i replace nearest matching word using php preg_replace ?

Was it helpful?

Solution

Use the following regular expression to capture everything between a dot character (.) and an underscore (_):

/\.([^_.]+)_/

Breakdown:

  • / - starting delimiter
    • \. - match literal dot (.) character
    • [^_.] - character class that matches any character that's not a . or _ one or more times
    • _ - match literal underscore (_) character
  • / - ending delimiter

The preg_replace() statement should look like:

preg_replace('/\.([^_.]+)_/', '.', $A);

Effectively, it says: "Replace everything between a . and _ with a .".

Output:

12854827.IDS.0 12854827.892.0
12854827.IDS.0 12854827.892.0

Demo

OTHER TIPS

Since you are using digit replace you can use this one:

preg_replace('/\.\d+_/', '.', $A);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top