Domanda

Qual è il modo corretto in PHP per affrontare le corde di decodifica, come queste:

Test1 \\ Test2 \n Test3 \\n Test4 \abc

L'output desiderato è:

Test \ Test2 (linebreak) Test3 \n Test4 abc

Una cosa che ho provato è stata:

str_replace(array('\\\\','\\n','\\'), array('\\',"\n",''), $str);

Ma questo non funziona, perché eseguirà la sostituzione due volte, il che causa:

\\n

Essere decodificato come una linea di rottura comunque.

Quindi stavo pensando a qualcosa del genere:

$offset = 0;
$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
while(($pos = strpos($str,'\\', $offset)) !== false) {

  $char = $str[$pos+1];
  if ($char=="n" || $char=="N") {
     // Insert a newline and eat 2 characters
     $str = substr($str,0,$pos-1) . "\n" . substr($str,$pos+2);
  } else {
     // eat slash
     $str = substr($str,0,$pos-1) . substr($str,$pos+1);
  }
  $offset=$pos+1;

}

Questo sembra funzionare, ma mi chiedevo se c'è forse un integrato che fa esattamente questo e l'ho perso completamente, o un modo del tutto migliore/più compatto per farlo.

È stato utile?

Soluzione

stripcslashes() quasi funziona, tranne per il fatto che non riconoscerà a e lo salta :(

$str = 'Test1 \\\\ Test2 \\n Test3 \\\\n Test4 \\abc';
echo stripcslashes($str);

Output questo ...

Test1 \ Test2 
 Test3 \n Test4 bc
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top