Advertisement Jump to content
Sign in to follow this  

Replacing occurances in a string

This topic is 4751 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm trying to turn occurances of a string into the number of the occurance in PHP For example: I want to replace the first occurance of "string" with "string #1" and the second occurance of "string" with "string #2", and the third occurance of "string" with "string #3", and so on How would I accomplish something like this? Sorry if this sounds a bit confusing

Share this post

Link to post
Share on other sites
Here's what I've just been able to come up with, pretty simple:

function MyCustomReplace($origStr, $replaceArray, $token )
// Counter for the index
$x = 0;

// The final string
$newStr = "";

// Only break up as many as mny replace words we have, if we are too short, the last instances are not replaced
$ar = explode($token, $origStr, count($replaceArray) + 1);

// Now we loop though all tokens of the string
for($a = 0; $a < count($ar) - 1; $a++)
$newStr .= ($ar[$a] . $replaceArray[$x++]);

// Add in the last part of the string
$newStr .= $ar[$a];

// Return the string
return $newStr;

// What we want to replace with
$replaceArr = array("|vowel1|", "|vowel2|", "|vowel3|");

// Replace all i's with the vowel string, *case sensitive*
echo MyCustomReplace("This is a test, is it not?", $replaceArr, "i");

/* Output:

Th|vowel1|s |vowel2|s a test, |vowel3|s it not?



I added in the 3rd param in explode to make sure no runtime errors will occur if you do not know how many instances to replace from. You could easily modify the functionality to loop back at 0 if $x was > then the number of elements to replace by. Oh yea, tested and works [wink] Should be self explanatory but if you need help with it feel free to ask!

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!