简体   繁体   中英

Regular expressions and preg_replace in PHP

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 "dog" 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.

Thanks in advance.

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);

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);

试试这个忽略所有字符:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM