Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I am trying to learning something about PHP, and I don't know how to do it, something like this:

I have a string:

$text = 'This is your post number [postnumb], This is [postnumb], And this is your post number [postnumb].';

And with PHP I want to change the string [postnumb] to the number of post:

$textchanged = 'This is your post number 1, This is your post number 2, This is your post number 3.';

Any help for me? Thanks.

share|improve this question
    
you want the same string [postnumb] to equal 3 different values – Dagon Jan 28 '14 at 3:07

2 Answers 2

up vote 2 down vote accepted

Using preg_replace(), you can use the 4th argument to limit the replacement to the first occurrence. Combine this with a loop that will run until there are no occurrences remaining, and you can achieve what you're after:

$text = 'This is your post number [postnumb], This is [postnumb], And this is your post number [postnumb].';

$i = 0;
while(true)
{
    $prev = $text;
    $text = preg_replace('/\[postnumb\]/', ++$i, $text, 1);

    if($prev === $text)
    {
        // There were no changes, exit the loop.
        break;
    }
}

echo $text; // This is your post number 1, This is 2, And this is your post number 3.
share|improve this answer
    
This is exactly what I want. Thank you. – user3242852 Jan 28 '14 at 3:23
    
Just more one question: /[postnumb]/ What represents /\ , \ and / ? Thanks. – user3242852 Jan 28 '14 at 3:32
    
@user3242852 preg_replace accepts a regex pattern, not a string. Regex patterns need a delimiter of your choice on either side of the expression, and special characters like []{}?. need to be escaped with a backslash. – Marty Jan 28 '14 at 3:34
    
Thanks, now I understand. – user3242852 Jan 28 '14 at 3:38
str_replace("[postnumb]", 1, $text);

You can't set different numbers for [postnumb] using str_replace() (unless you do it manually for substrings).

preg_replace() should help you for that case, or using different tags for different numbers (like [postnumb2] and [postnumb]).

share|improve this answer
    
Thank you... :D – user3242852 Jan 28 '14 at 3:24

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.