2

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 ?

0

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

why u use ([^_.]+) in regex
@lintocheeran: Are you sure you're seeing the latest version of this answer? I've already explained this in the answer. It is used to match everything between a . and _. See Regex101 demo
0

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

preg_replace('/\.\d+_/', '.', $A);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.