Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Replace String while upping number to replace with 1

Status
Not open for further replies.

Zilflic

Programmer
Feb 23, 2005
17
US
Hi,

I would like to do something similiar to the following:
Code:
$counter = 1;
$year = "year: NDX     year: NDX";
$year = str_replace("NDX", $counter++, $year);
and get the result:

year 1 year 2

It echos out 1 for both years, so how would you guys go about getting this result? I made this example up to demonstrate my problem, the code is a lot more complex...

Thanks,

Ann
 
Try
Code:
$year = str_replace("NDX", ++$counter, $year);

$var++ increments after the variable is used.
++$var increments before the variable is used.

Ken
 
It looks to me like you need to read up on PHP's pre-increment operator here:
But you can't use str_replace with the "needle" value of "NDX", as the function will replace both "NDX" strings.

You'll have do something like:

$year = str_replace (" year: NDX", " year: " . ++$counter, $year);

Although:

$counter++;
$year = str_replace (" year: NDX", " year: " . $counter, $year);

is probably more readable.


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Here is a solution using a regular expression:
Code:
$y = 1;
$text = "year nnn year nnn year nnn year nnn year nnn";
$pattern = '/nnn/e';
$text = preg_replace($pattern,'$y++',$text);
echo($text);
The 'e' pattern modifier evaluates the replacement paramater as PHP code for each replacement.
 
Thanks DRJ478! That is exactly what I was looking for. Unfortunately I don't think I made myself clear enough and you saved me from figuring out how to repeat myself a different way.

It wasn't an operator problem I was having. It was a lack of knowing which function to use.

Thanks again!

Ann

 
in retrospect I should have put at least three years in my example...
 
Part of getting good answers is asking good questions. All members of TT appreciate it if posters learn through the answers and not only acknowledge the solution but also try to learn how to ask the questions in a better way. A true professional is always ready to learn, so are you. You're on your way!
Cheers,
DRJ
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top