Removes spaces produced by line breaks

Asked

Viewed 154 times

-2

Because the code below does not remove spaces, only line breaks?

$urlCorreios = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?
   nCdEmpresa=&
   sDsSenha=&
   nCdFormato=1&
   nVlDiametro=0&
   sCdMaoPropria=n&
   sCdAvisoRecebimento=n&
   nCdServico=" . $cod_servico . "&
   sCepOrigem=" . $cep_origem . "&
   sCepDestino=" . $cep_destino . "&
   nVlPeso=" . $peso . "&
   nVlAltura=" . $altura . "&
   nVlLargura=" . $largura . "&
   nVlComprimento=" . $comprimento . "&
   nVlValorDeclarado=" . $valor_declarado . "&
   StrRetorno=xml";

echo preg_replace('/[\n\r\t]/', '', $urlCorreios);
  • Just complementing, you used [\n\r\t]. The brackets define a character class, and corresponds to any character within them. So this regex means: "a \n or one \r or one \t". None of these characters match the whitespace :-)

2 answers

3


And why not just use a native function, like http_build_query()? Example:

$urlCorreios = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx";

$data = array(
    "nCdEmpresa" => "",
    "sDsSenha" => "",
    "nCdFormato" => "1",
    "nVlDiametro" => "0",
    "sCdMaoPropria" => "n",
    "sCdAvisoRecebimento" => "n",
    "nCdServico=" => $cod_servico,
    "sCepOrigem=" => $cep_origem,
    "sCepDestino=" => $cep_destino,
    "nVlPeso=" => $peso,
    "nVlAltura=" => $altura,
    "nVlLargura=" => $largura,
    "nVlComprimento=" => $comprimento,
    "nVlValorDeclarado=" => $valor_declarado,
    "StrRetorno" => "xml"
);

$urlCorreios = $urlCorreios . '?' . http_build_query($data);

echo $urlCorreios . "\n";

Another advantage of this is that you wouldn’t have to urlencode() values and keys, plus it will be easier than using string and will be able to handle the array at any time with native array functions in PHP.

Something else, use \s, as it is in the other answer, without treating variable by variable with urlencode (chance don’t use http_build_query) will give problem for sure, although only the no use of urlencode would already be a problem.

  • 1

    Caramba had never seen this http_build_query() function and had some problems with line breaking, thanks for the tip mano.

2

Try adding a \s no regex. Thus:

echo preg_replace('/[\s\n\r\t]/', '', $urlCorreios);

  • 2

    \s already encompasses the \n, \r and \t, then it might just be preg_replace('/\s/', '', $urlCorreios)

  • ok. thank you very much!

  • 2

    @hkotsubo exactly, is redundant. It is not even necessary to [...], would suffice something like '/\s+?/'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.