phpregexreplacepreg-replace

Remove non-digital characters found in an alphanumeric substring occurring after a specified character


I have strings like this (some examples):

I need to use PHP with preg_replace() and regular expressions to delete all non-numeric characters in any string, after the forward-slash.

For example the codes above would look like this afterwards:


Solution

  • To remove all \D anywhere after a / you could replace:

    (?:/\K|\G(?!^))(\d*)\D+
    

    with $1. Like:

    preg_replace(',(?:/\K|\G(?!^))(\d*)\D+,', '$1', $str);