How to remove whitespace from a string with Regex in PHP?

Asked

Viewed 4,410 times

-2

What a PHP Regex would look like to eliminate more than one blank space from one string?

For example, <img src=' smiley. gif'> I’d like you to stay <img src='smiley.gif'>.

  • 3

    The question to ask is: why are there spaces in the image path?

  • I hadn’t read it properly, I updated the response

  • 2

    Following the thought of @Andersoncarloswoss I strongly advise you to review your code and try to understand why the link of your image contains these spaces.

3 answers

5

You have requested Regex, but do not need it, if you have access to the attribute content you can use string more efficient:

$com = "'  smiley. gif'";

$sem = str_replace(' ', '', $com);

If you have more characters to replace, you can put in the first parameter:

// remover espaço, tab e quebra de linha \n

$com = "'  smiley. gif'";

$sem = str_replace(array(' ', "\t", "\n"), '', $com);

Handbook https://secure.php.net/manual/en/function.str-replace.php

Now, the ideal is to fix the source of the data so you don’t even need it.

1

Use the ltrim command to remove the start space and rtrim to remove from the end. Or just Trim to remove from the end and start:

echo ltrim("    |ola mundo|");

to remove space has str_replace

echo str_replace(" ", "", " ola mundo.jpg");

If you want a regex:

echo preg_replace("/\s+/", "","    ola mundo");
  • 2

    updated response

1

The question this vague, can not know if the input will be just an image or can be an HTML with multiple images, if it is the second case so initially you should preferably manipulate the DOM, for example:

$myhtml = "
<p>
    <img src='  smiley1. gif'>
    <img src='  smiley2. g if'>
    <img src='  smiley3. gi f'>
    <img src='  smiley4 . gif'>
</p>
";

$doc = new DOMDocument;

//Carrega e interpreta a string
$doc->loadHTML($myhtml, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);

//Pega todas as imagens dentro do documento
$imgs = $doc->getElementsByTagName('img');

//Faz o loop para remover o espaço um a um de cada imagem
foreach ($imgs as $img) {

    //Pega o atributo SRC de cada imagem
    $src = $img->getAttribute('src');

    //Aqui pode usar a solução do Bacco ou do Ricardo
    $src = preg_replace('#\s+#', '', $src);

    //Atualiza o atributo SRC
    $img->setAttribute('src', $src);
}

//Mostra resultado
echo $doc->saveHTML();

Note that I used:

  • LIBXML_HTML_NOIMPLIED prevents adding html and body tags
  • LIBXML_HTML_NODEFDTD prevents adding the Doctype

Online example: https://repl.it/@inphinit/remove-Spaces-in-src-attributesphp


Note that if you want to display HTML without it being "executed" (interpreted) by the browser you should use htmlspecialchars, example:

//Mostra resultado
echo htmlspecialchars( $doc->saveHTML() );

Related: What is the difference between htmlspecialchars() and htmlentities()?

Browser other questions tagged

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