Search code examples
phpregexvariablescapturing-group

PHP regex combine capturing group variable with a number


For example, I want to replace: margin:0px; with margin:0;
This is the regex I came up with: $data = preg_replace('/([^\d])0px/', '$1 0', $data);

$1 would represent the : in this example.

Now how do I combine $1 with a number without php interpreting it as another capturing group variable and without using whitespace as I did above?


Solution

  • You can use '${1}0'. See PHP documentation on strings for more information.

    The preg_replace documentation also discusses this.

    Incidentally, you could use this regex instead (in 5.2.4 and up):

    $data = preg_replace('/\D0\Kpx/', '', $data);
    

    \D matches anything that is not a digit, equivalent to [^\d].

    \K requires that everything that comes before it to match, but excludes it from the match itself. Thus you don't have to store the first part of the pattern and include it in the replacement.

    Here is the documentation on escape sequences.