문제

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.

Here is the documentation on escape sequences.

다른 팁

are you trying to do something like this ?

<?php

function replace_px($val, $new_val, $str) {
  return $new_str = str_replace($val . "px", $new_val, $str);
}

$str = "margin:0px;";
echo replace_px(0, 0, $str);

?>

// Output

margin:0;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top