0

I want to replace each instance of a given string with a number.

ex:

<?php

$string = "Hello Foo Text Apple"
preg_replace($pattern, $pattern.$i++, $string);

//output    
Hello0 Foo1 Text2 Apple3

?>

the $pattern is a regex query but in this case I have used plain text

2
  • You want to replace or append the number? Commented Jan 29, 2011 at 17:20
  • @jwerre: I want to append a number/string Commented Jan 29, 2011 at 17:31

2 Answers 2

2

If you are using PHP 5.3:

$string = "Hello Hello Hello Hello";
$i = 0;
preg_replace_callback($pattern, function($matches) use ($i) {
    return $matches[0].$i++;
}, $string);
Sign up to request clarification or add additional context in comments.

Comments

1
$string = "Hello Hello Hello Test Hello Test";

$i = 0;
$string = preg_replace("/\w+/e", '$0 . $i++', $string);

2 Comments

Thanks, but the increments must not stop. eg. Hello1 Test2 Something3
@dany: Updated code. Set $i to what you want the count to start at.

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.