Ben Alan
Ben Alan

Reputation: 1695

Replace a blacklisted word even if it has extra characters between matching characters

I'm using preg_replace() and I need some help. I've been trying to do this for some time and it's time to face facts: I am really bad with regular expressions. I'm not even sure what can and can't be done with them.

Lets say I want to change the string dogs to cats no matter how much white space is between them. how do I do it?

dogs -> cats
d o g s -> c a t s

I have tried:

preg_replace("/D\s*O\s*+G/", "cat", $string);

and the string comes back with all "d o g" unchanged.

Next question: Is it possible to ignore characters between letters and not just white space?

d.o g.s -> c.a t.s
dkgoijgkjhfkjhs -> ckgaijtkjhfkjhs

And finally, when it comes to whole words, I can never seem to get the function to work either.

display: none -> somestring
display    :    none -> somestring

Often times I just cause $string to return empty.

Upvotes: 1

Views: 437

Answers (3)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

Try this to ignore all characters:

$res = preg_replace('~d([^do]*+)o([^g]*+)g([^s]*+)s~i' , 'c$1a$2t$3s', $string);

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324780

One problem is that you're not allowing it to recognise d and D as the same thing. To do that, just put i after the last / as a modifier.

Your \s can be anything you want to allow - in this case, you might want . to allow all characters (except newlines, except except with the s modifier added).

So try something like this:

$string = preg_replace("/d(.*?)o(.*?)g/i","c$1a$2t",$string);

Note that this will mean that DOG becomes cat. If you want to keep cases, try this:

$string = preg_replace_callback("/(d)(.*?)(o)(.*?)(g)/i",function($m) {
    return
        ($m[1] == "d" ? "c" : "C")
        .$m[2]
        .($m[3] == "o" ? "a" : "A")
        .$m[4]
        .($m[5] == "g" ? "t" : "T");
},$string);

Upvotes: 3

Orangepill
Orangepill

Reputation: 24655

Regular expressions are case sensitive

You will have to use

preg_replace("/[Dd]\s*[Oo]\s*+[Gg]/", "cat", $string);

or use the case insensitve modifier

preg_replace("/D\s*O\s*+G/i", "cat", $string);

If you want to match with characters other then space your just need to change your \s references to something that matches the allowed characters for example:

preg_replace("/D\W*O\W*+G/i", "cat", $string);

Upvotes: 0

Related Questions