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:
- before “Colore”
- “Colore”
- after “Colore” to beginning of “Lunghezza”
- “Lunghezza”
- after “Lunghezza”
And then wrap 1
, 2 and 3
, and 4 and 5
in <p>
and </p>
.
JavaScript
x
<?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
JavaScript
<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