user2064000
user2064000

Reputation:

str_replace for UTF-16 characters

I have some strings containing characters such as \x{1f601} which I want to replace with some text.

When I do this using preg_replace, it would be something like:

preg_replace('/\x{1f601}/u', '######', $str)

However, this doesn't seem to work with str_replace:

str_replace("\x{1f601}", '######', $str)

How can I make such replacements work with str_replace?

Upvotes: 1

Views: 895

Answers (1)

Martin
Martin

Reputation: 22760

preg_replace is a Regex parser/replacer, which is a Perl Regular expression engine, but str_replace is NOT and replaces things with a plaintext method

The Preg_replace you have got can be seen here in regex101, stating that:

matches the character 😁 with position 0x1f601 (128513 decimal or 373001 octal) in the character set

But this could be transferable to a non-regex find and replace,by copy and pasting that face smiley symbol into the str_replace directly.

$str = str_replace("😁", '######', $str)

Or, by reading deceze's comment which gives you a clean, small solution.

Additional:

You are using a character set that is non-standard so it may be useful for you to explore Mb_Str_replace (gitHub) which is an accompanyment (but not directly from) the mb_string collection of PHP functions.

Finally:

Why do you need to do string replace whe you are already doing regex preg_replace? Also please read the manual which states all of this fairly clearly.

Upvotes: 2

Related Questions