I have this code
<?php
$source[]="clock=1,time=1,stamp=3,color=33";开发者_如何学C
$source[]="clock=2,time=1,stamp=1,color=61";
$label="clock";
$what=$label."=(\d)";
$this="clock=0";
for($i=0; $i<3; $i++)
{
$new_source=preg_replace( $what,$this,$source[$i],$count);
echo $new_source;
};
?>
I need to replace $label=1; or $label=x with $label=0 but the x is variable.
First off the bat, don't use $this. Rename it to, for example, $replacement. $this is a reserved variable in PHP5.
Next, you don't need $count in pre_replace.
Finally, wrap $what in a delimiter (such as /).
$new_source=preg_replace( '/'.$what.'/',$replacement,$source[$i]);
<?php
$source[]="clock=1,time=1,stamp=3,color=33";
$source[]="clock=2,time=1,stamp=1,color=61";
$label="clock";
$what="/$label=(\d)/";
$to="clock=0";
for($i=0; $i<3; $i++)
{
$new_source=preg_replace( $what,$to,$source[$i]);
echo $new_source;
};
This is now correct. The problems were:
- You used a variable named $this to store the replace target string, which is incorrect because PHP refers to the current object with the variable $this in an object-oriented context.
- You passed a parameter named $count to preg_replace which had no value.
精彩评论