Php replace double backslash group

how to replace a double backslash group in a string with *

eg:

\\\\a ->  **a
\\\a  ->  *\a
\\a   ->  *a
\a    ->  \a

I try to use both str_replace, and so preg_replace, but this failed in the second case

str_replace('\\', '*', $str);
preg_replace('/\\\\/', '*', $str);

=> `\\\a` -> `**a`

the reason I want to do this is because I want something the same as Split a string by separator, but not if it is escaped , but

$str = '1|2\|2|3\\|4\\\|4';
$r   = preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $str);
var_dump($r);

give me.

  0 => string '1' (length=1)
  1 => string '2\|2' (length=4)
  2 => string '3\|4\\' (length=6)
  3 => string '4' (length=1)

I expect something like

  [0] => 1
  [1] => 2\|2
  [2] => 3\\
  [3] => 4\\\|4

php 5.4.45-2

+4
source share
1 answer

The literal backslash in single-line PHP strings must be declared using two backslashes: 1|2\|2|3\\|4\\\|4you need to print $str = '1|2\\|2|3\\\\|4\\\\\\|4';.

​​ 4 .

PHP:

$str = '1|2\\|2|3\\\\|4\\\\\\|4';
// echo $str . PHP_EOL; => 1|2\|2|3\\|4\\\|4
$r   = preg_split('~\\\\.(*SKIP)(*FAIL)|\\|~s', $str);
var_dump($r);

:

array(4) {
  [0]=>
  string(1) "1"
  [1]=>
  string(4) "2\|2"
  [2]=>
  string(3) "3\\"
  [3]=>
  string(6) "4\\\|4"
}

**a \\a,

$str = '\\\\a';
$r   = preg_replace('~\\\\~s', '*', $str);

+3

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


All Articles