How would a RegEx in PHP eliminate more than one blank string ?
For example, <img src=' smiley. gif'>
would like you to <img src='smiley.gif'>
.
How would a RegEx in PHP eliminate more than one blank string ?
For example, <img src=' smiley. gif'>
would like you to <img src='smiley.gif'>
.
You have requested RegEx, but do not need to, if you have access to attribute content you can use more efficient string operations:
$com = "' smiley. gif'";
$sem = str_replace(' ', '', $com);
If you have more characters to replace, you can by in the first parameter:
// remover espaço, tab e quebra de linha \n
$com = "' smiley. gif'";
$sem = str_replace(array(' ', "\t", "\n"), '', $com);
Manual link
Now, the ideal is to fix the source of the data so you do not even need it.
Use the ltrim command to remove the boot 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");
The question is vague, you can not tell if the input will be just an image or it may be an HTML with several images, if it is the second case then you should initially 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 Doctype Example online: link
Note that if you want to display HTML without it being "executed" (interpreted) by the browser you should use htmlspecialchars
, eg
//Mostra resultado
echo htmlspecialchars( $doc->saveHTML() );
Related: What is the difference between htmlspecialchars () and htmlentities ()?