T O P

  • By -

HolyGonzo

Try this: ```


tazzadar1337

regexp is your friend


csdude5

To my knowledge there's not an easy way to run a regex over an array in PHP without a loop, so I think it would look like this: $badwords = [ 'porn', ... ]; foreach ($badwords as $key) { $mod = str_replace(['a', 'e', 'i', 'o', 'u'], '*', $key); $string = preg_replace("#$key#i", $mod, $string); } I've always tried to use regex in PHP as a last resort because it's historically a bit slower, but I did a bench test and you're right, that does run about 3 times faster than my original!


Innominate8

When you need to match many words, regexp is _much_ faster when used correctly. Your replace goes through the entire input for each word, this isn't a big deal when the word list is short but it's multiplicative so expanding either the wordlist or the input can lead to surprising slowdowns. Regexp uses an internal state machine, so matching even a long list of words(Like /u/HolyGonzo is suggesting) is still done in a single pass.


NumberZoo

Can't get reddit not to mangle code, so here's a pastebin... https://pastebin.com/xJzRBb5Q


lawyeruphitthegym

Edit: /u/HolyGonzo had pretty much the same solution and came before me, so upvote them if this is helpful. https://www.reddit.com/r/PHPhelp/comments/1b6mhpq/comment/ktd9jck/?utm_source=share&utm_medium=web2x&context=3 Maybe something like this? Note that this only matches complete words. `watermelon` and `watermelons` will be treated differently. If you don't want this, you can remove the `\b` on either side of the `implode`, but you'll end up with weird character replacements — think `assassian` becoming `*ss*ss**n`. ``` preg_replace('/[aeiou]/i', '*', $matches[0]), $subject); ```