Mask of all characters with preg_replace, except for some needles

With PHP preg_replace and regex

$string_1 = "leave sb. alone";
$string_2 = "pick one way forward";
$string_2 = "suffer from sth.";

I need to mask each line with the specified character, but leave the spaces, apostrophe and some line untouched, for example:

$mask_1 = "XXXXX sb. XXXXX";
$mask_2 = "XXXX XXX'X XXX XXXXXXX";
$mask_2 = "XXXXXX XXXX sth.";

In this case, I want to save: sb. STG. spaces and apostrophe. Any help would be greatly appreciated.

with $mask_1 = preg_replace('/(sb.\K)?./s', 'X', $string_1);i leave only 'sb.' but the gaps are still changing.

PS: Both @Casimir et Hippolyte and @Wiktor Stribiżew answers are great solutions, but I took Wiktor to implement and explain SKIP-FAIL. Thank you very much!

+4
source share
2 answers

You can use the SKIP-FAIL regular expression:

'~(?:s(?:b|th)\.|[\s'])(*SKIP)(*F)|.~'

Watch the regex demo

More details

  • (?:s(?:b|th)\.|[\s']) - s, b (sb), th (sth), . ' ([\s'])
  • (*SKIP)(*F) -
  • | -
  • . - char, linebreak char ( DOTALL, )

, , , \b (, '~(?:\bs(?:b|th)\.|[\s'])(*SKIP)(*F)|.~').

+1

, :

(?:\G|\b(?!sb\.|sth\.))[[:alnum:]]

( [[:alnum:]] \w [^\W_])

, \K , :

\G(?:\W*(?:\bs(?:b|th)\.)?)*+\K.

\G .

+1

Source: https://habr.com/ru/post/1662836/


All Articles