简体   繁体   中英

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?

将正则表达式模式使用负前瞻(?!...) ,例如

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

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM