0

My code is:

preg_replace('/[中]/', '1', '中,博文大,精中深');

Why the result is:

111,博文大,精111深

The Chinese character '中' should be replace once, while triple instead.

Any help? Thanks

ccbility
  • 25
  • 3

1 Answers1

2

First of all, please read this article about unicode characters in regexps. Next, you may need this article about modifiers. I think that you need u modifier in your regexp.

preg_replace('/[中]/u', '1', '中,博文大,精中深');

Please, also read comments in modifiers article for more examples.

Also, for simple replaces like in example above you can use str_replace.

str_replace('中', '1', '中,博文大,精中深');
marv255
  • 808
  • 6
  • 19
  • It works.I know how to avoid it, but you help me figure it out essentially.Thank you very much. Still a little question: why it replace or match three time without u modifier? Anyway, I know how to deal it in a right way. – ccbility Oct 18 '17 at 06:35
  • I think trouble is in a fact that unicode characters are multibytes, so regexp can't understant that you want to replace all octets with your symbol and replaces each octet. But i'm not sure about it. – marv255 Oct 18 '17 at 07:13