Jump to content
  • Advertisement
Sign in to follow this  
zealotgi

Replacing occurances in a string

This topic is 4650 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
Advertisement
Here's what I've just been able to come up with, pretty simple:

<?php
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 GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!