DeryckOE
DeryckOE

Reputation: 105

Replace only the last occurrence of <br /> in a string

This is an example content (in spanish)

Definición<br /> Elementos del fuego<br /> Clases de fuego, ¿Cómo evitar que comiencen las clases de fuego?<br /> Métodos de extinción<br /> Tipos de extintores portátiles<br /> Forma de usar los extintores portátiles<br /> Protección pasiva para el control de incendios, tipos de componentes.<br /> Procedimientos preventivos en caso de incendios en minería<br />

I want to remove the last <br /> occurrence using php preg_replace().

I have tried with

preg_replace('/<br \/>$/', '<br class="last" />', $content);

but does not woks. The compiler trows an error.

What can I do please?

Upvotes: 0

Views: 5366

Answers (2)

Bart Kiers
Bart Kiers

Reputation: 170148

Note that when using regex with look ahead:

$text = "foo bar <br /> \nbaz <br /> <br /> mu";

echo preg_replace('/<br \/>(?!.*<br \/>)/', '<br class="last" />', $text) . "\n";

will cause two <br /> to be replaced since the . (dot) meta char does not match line breaks. So the above will print:

foo bar <br class="last" /> 
baz <br /> <br class="last" /> mu

You might also want to account for "<BR>" or "<br   />" (more than one space).

echo preg_replace('#<br\s*/?>(?!.*<br\s*/?>)#is', '<br class="last" />', $text) . "\n";

(the i makes the pattern case-insensitive, and the s lets . match line break chars as well)

which will print:

foo bar <br /> 
baz <br /> <br class="last" /> mu

If you're sure the needles will always look like <br />, then a couple of str-operations would also do the trick:

$text = "foo bar <br /> \nbaz <br /> <br /> mu";
$needle = "<br />";
$index = strrpos($text, $needle);

if($index) {
  echo substr_replace($text, '<br class="last" />', $index, strlen($needle)) . "\n";
}

Upvotes: 1

Ωmega
Ωmega

Reputation: 43673

Use regex pattern with negative lookahead (?!...), such as

<br \/>(?!.*<br \/>)

Upvotes: 5

Related Questions