php - Regex replace word while keeping capitalisation -


i'm trying create regular expression replace word. instance, want replace word "dog" "cat". don't want replace dogmatic or robodog.

i'm using now:

<?php  $str = preg_replace("/dog\w/", "cat", $str); ?> 

but have multiple problems it. one, if use "i" note don't care capitalisation, replacement string doesn't use same capitalisation. furthermore, "the dog eats" becomes "the cateats" (without space).

can me reliable solution replace words, including following cases: "dog" -> "cat" "a dog, sheep" -> "a cat, sheep" "my dog" -> "my cat" , dog becoming cat, etc

the easiest way create 2 regular expressions , pass them array preg_replace:

preg_replace(array("/\bdog\b/", "/\bdog\b/"), array("cat", "cat"), "dog eats dog"); 

returns:

"cat eats cat" 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -