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?
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.