preg replace - PHP preg_replace multiple rules
Get the solution ↓↓↓Solution:
First you need to be explicit about the replacement conditions, your rules say 'not at the begining of a word and not before/after a vowel' but you have not implemented that in the regex. You can do this using Negative Lookahead/Lookbehind. For example:
- Replace a, i, o with u (if not at the beginning of a word & if not before/after a vowel)
Can be implemented with:
{-code-1}
This method can be used to implement the first 3 rules.
The next problem is that 'fox' and 'dog' will be affected by the first 3 rules, so you should replace the changed version to 'wolf' and 'cat'. So for dog => cat:
{-code-2}
Note: Because of the way preg_replace works with arrays, it's much better to not use indexes in the $patterns and $replacements arrays, since these can be misleading. Use the [] operator in pairs like I did above, so you always know what goes with what.
Part 2:
Aha. I see. You need to make the replacement exlusive.
You could use a regex that matches both the first cases, which are the problematic ones. Then you can use an interesting weird feature of preg_replace: When you add thee
modifier, the replace string is instead evaluated as PHP code. Combining this with capturing groups, it will allow you to decide whether to output au
or ani
according to what you matched.
$patterns[] = "/(?<!\b|[aeiou])([aeiou])(?![aeiou])/e";
$replacements[] = '("$1" == "e" || "$1" == "u")? "i":"u"';
*Note the /e and the () around the vowel matching class.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: foreign key constraint is incorrectly formed laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.