简体   繁体   中英

Regular expression replace whole words in PHP

I have an expression like:

$x="We have a cat here.";

I want to replace "a" with, for example 5, so this should look like:

We have 5 cat here. //It doesn't make sense, but it's just an example.

I tried simple

echo str_replace("a","5",$x);

but that returned

We h5ve 5 c5t here.

Then, I tried

echo str_replace(" a "," 5 ",$x);

but that didn't do the job for strings like

We have a cat here. (A dog actually).

I decided to use regex, but Im completely newbie to this, and I don't know how to use any of them... Well, I'd really appreciate any link to a good tutorial, but I need the answer quite fast...

使用\\b标记单词边界,例如

$newstring = preg_replace('/\b[Aa]\b/', '5', $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