0

I have this code

<?php

$source[]="clock=1,time=1,stamp=3,color=33";
$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.

3
  • What is the problem? AFAIK this code does just that. Commented Mar 24, 2011 at 12:57
  • From the look of it, it's actually replacing clock=1 with clock=clock=0 Commented Mar 24, 2011 at 13:01
  • No, it is not. It is matching clock=n and replacing it with clock=0 Commented Mar 24, 2011 at 13:03

2 Answers 2

1

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanx I'll try this right away. PS: $this was just for example :) i don't use it
0
<?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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.