For example, the following code wraps each matching character with an <i> tag.
echo preg_replace('/[aeiou]/', '<i>$0</i>', 'alphabet');
// result: <i>a</i>lph<i>a</i>b<i>e</i>t
But I’d like it to only replace each character once.
I’m looking for a result like <i>a</i>lphab<i>e</i>t, where the second a makes it through without a tag because the search string only has one a.
Can you help? Is this possible without of iterating through each character in an foreach loop?
The answer should also allow for two or more of the same characters, each only to be used once. For example, if I were searching for aaeioo in the string alphabetsoupisgood, it should match both of the a‘s but only two of the three o‘s.
If you just want a letter to be replaced only once then following regex should work:
OUTPUT:
PS: Note that it replaces last occurrence of a letter instead of the first one.
EDIT:
Following would produce the same output as expected by the OP (thanks to @AntonyHatchkins):
EDIT 2:
Upon OP’s comment:
Can you help me allow more than one a then? How can I match 2, but not 3 a'sI am posting this answer:
EDIT 3:
Upon another of OP’s comment:
that will allow duplicates for all characters in the string, not just 2 a's & 1 eI am posting this answer:
OUTPUT:
Note: I believe original problem has already changed so many times so please don’t add further complexity in this problem. You’re free to post another question if you have different queries.