Skip to content
Advertisement

PHP function to insert html tags before specific characters [closed]

I have a challenge where I have some dynamic text which have striped all HTML tags so on my end become a little weird. For example:

Composizione tessuto: sottoveste: 95% viscosa, 5% elastan, parte superiore: 100% poliestere. Manica lunga Tessuto leggeroColore:BiancoLunghezza:Mini

In all texts there is Colore and Lunghezza at the end but as you can see it’s one word.

What would be the best way to insert HTML tag p before Colore and Lunghezza so it’s become more readable?

Advertisement

Answer

You can use regex to split the string into few parts:

  1. before “Colore”
  2. “Colore”
  3. after “Colore” to beginning of “Lunghezza”
  4. “Lunghezza”
  5. after “Lunghezza”

And then wrap 1, 2 and 3, and 4 and 5 in <p> and </p>.

<?php
$re = '/^(.+)(Colore)(.+)(Lunghezza)(.+)$/m';
$str = 'Composizione tessuto: sottoveste: 95% viscosa, 5% elastan, parte superiore: 100% poliestere. Manica lunga Tessuto leggeroColore:BiancoLunghezza:Mini';
$subst = '<p>$1</p><p>$2$3</p><p>$4$5</p>';

$result = preg_replace($re, $subst, $str);

The result is then

<p>Composizione tessuto: sottoveste: 95% viscosa, 5% elastan, parte superiore: 100% poliestere. Manica lunga Tessuto leggero</p><p>Colore:Bianco</p><p>Lunghezza:Mini</p>

Live example: https://regex101.com/r/2aGxB0/1

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement