1

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.

1
  • you want the same string [postnumb] to equal 3 different values Commented Jan 28, 2014 at 3:07

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

2 Comments

Just more one question: /[postnumb]/ What represents /\ , \ and / ? Thanks.
@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.
0
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]).

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.