Home php How to apply preg_replace considering utf8 encoding

How to apply preg_replace considering utf8 encoding

Author

Date

Category

Guys, maybe the table of contents of the question was not very well composed, but the essence is as follows:

I have lines like this:

"I'm trying" program (includes 3 smart-workouts within 2 weeks) at any time, for only 1650 rubles, instead of 3300 rubles.
The "Slender Spring" program (includes 6 smart-workouts per month) from 7.30 to 17.00, for only 2499 rubles, instead of 6000 rubles.
The Slender Spring program (includes 6 smart workouts per month) from 7.30 to 17.00, for only 2499 rubles, instead of 6000 rubles.

I need to secure myself to send to json.

For this, I want to remove all legs in different variations from the string.

If I:

$ text1 = preg_replace ('/ [\ "\" \' \ "] / ',' ', $ text1) ;

Then I get the output

Program I try (includes 3 smart workouts over 2 weeks) at any time, for only 1650 rub., instead of 3300 rub.

How to fix this, and also I need to shorten the line to max. up to 128 characters


Answer 1, authority 100%

Just use the native json_encode , it escapes everything:

$ str = "I'm Trying" program (includes 3 smart workouts over 2 weeks) anytime, in just 1650 rubles instead of 3300 rubles ";
$ json = json_encode ($ str);
var_dump ($ json);

To shorten the string, use mb_substr :

$ str = mb_substr ($ str, 0, 128);
$ json = json_encode ($ str);

Answer 2, authority 95%

add / u

$ text1 = preg_replace ('/ [\ "\" \' \ "] / u ',' ', $ text1 );

http://php.net/manual/en/reference. pcre.pattern.modifiers.php

u (PCRE_UTF8)
This modifier includes additional PCRE functionality that is not Perl compatible: the template and target string are treated as UTF-8 strings. An invalid target string causes the preg_ * functions to find nothing, and an invalid pattern results in an E_WARNING level error. The fifth and sixth octets of the UTF-8 sequence are considered invalid as of PHP 5.3.4 (as per PCRE 7.3 2007-08-28); they were previously considered acceptable.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions