NOTE: If you don’t want to read this, check “TLDR” version at bottom of this comment.
I currently have a basic BBCode class.
When an user makes a comment, he can use [item] [/item] tags. Anything written between [item] [/item] tags are automatically converted to their 32x32px images, and a onHover effect to load item status with ajax.
For example, you can make comments like this:
[item]Cloth Armor[/item]
[item]Wooden Sword[/item]
[item]Iron Shield[/item]
PHP will automatically show image of “Cloth Armor”. When you hover this image, you can see additional information about this item. (e.g how much defense bonus it gives)
It’s all basic, however, I don’t want to force my users to use [item] [/item] tags. I want to convert every string that is a “item name” to be converted automatically.
Let’s say, user made a comment like this, without using the BBCodes.
Hello, my characters needs some defense so I bought a Cloth Armor. Then, I will buy Wooden Sword and Iron Shield.
Okay, we can do this in many ways, but I want to get it done with LEAST steps as much as possible.
For example, something like this works but I don’t want to use such function:
$itemsArray = array('Iron Shield', 'Wooden Sword', 'Cloth Armor');
$comment = $_POST['comment'];
foreach($itemsArray as $k => $v)
{
str_replace($v, "onHoverEffect:$v", $comment);
}
echo $comment;
This script would loop the string countless of times. (actually, there are 300+ items in the database, so it would loop 300 times, searching and replacing each item one by one, making such a huge & unnecessary load.)
I want a guidance or an example about how can this be done in a “single loop”. It should start from the first letter of string. For any correct item name he finds (item names are in the array), it should call the replace function, but generally, never loop the entire string more than once.
Too Long – Didn’t Read Version
- An user made a comment like “New York is more crowded than Las Vegas”.
- You have an array of city names in database. (New York, Las Vegas, Moscow etc.)
- You should be “uppercasing” city names found in the comment only with a “single loop”. (you won’t be using foreach $cities)
I want a guidance or an example about how can this be done in a “single loop”.
strtr()is very fast.You could use it to make your replacements.
CodePad.
Note that
strtr()doesn’t make any distinction between words on their own or a grouping of characters. If you wanted words on their own, you’d have to use a regular expression with word boundaries (\b) or roll something similar.CodePad.