How to replace "cat" in a given string by "FELIX" but not if it's followed by special character like "- or _ or :"
example :
"my cat is hungry all the time" => "my Felix is hungry all the time"
"the products cat-1547 and cat:154 are disponible now" => "the products cat-1547 and cat:154 are disponible now"
thanks
Use a negative lookahead together with word boundaries:
/\bcat\b(?![-:])/
See the regex demo
Pattern explanation:
\b
- leading word boundary (to avoid matching cat
in tomcat
)cat
- a literal string cat
\b
- trailing word boundary (i.e. the next char must be a non-letter, non-digit and non-underscore character, and it prevents from matching cat
in catwalk
)(?![-:])
- a negative lookahead that fails the match if a -
or :
immediately follows the cat
.$re = '~\bcat\b(?![-:])~';
$str = "my cat is hungry all the time
the products cat-1547 and cat:154 are disponible now";
$subst = "Felix";
$result = preg_replace($re, $subst, $str);
echo $result;
In python you can :
(cat)(?![-:])
?! checks that the expression isn't followed by what's after ?!