Miguel Gisbert
Miguel Gisbert

Reputation: 113

Remove or strip html tags and put them back again at the same position for a php string

I was looking for a way to remove html tags from a string and put them back at the same position after sending the string to translate with deepL (which doesn't work with html tags in case they have attributes).

I'll post the solution bellow.

Upvotes: 0

Views: 1069

Answers (2)

Serge Tkachuk
Serge Tkachuk

Reputation: 1

https://gist.github.com/fly304625/baa9d1d98d26c507a5b0731d00d04c2a - this example only looks at Deepl tags, not all other tags indiscriminately. Some tags may need to be preserved for certain purposes.

Upvotes: 0

Miguel Gisbert
Miguel Gisbert

Reputation: 113

SOLUTION:

Here's how you guys can remove and recover all the html tags in the same order in case you need to translate the string with DeepL like me or do something else which needs no html tags at the string.

https://gist.github.com/miguelgisbert/7ef9ee15aa0cc1ba32ea5ed192e486c3

$str1 = "<p style='color:red;'>red</p><strong style='color:green;'>green</strong>";
$pattern = '/<[^>]+>/';

preg_match_all($pattern, $str1, $matches);
$replacements = $matches[0];
$str2 = preg_replace($pattern, '<>', $str1);

// TRanslate $str2 with DeepL or do whatever without html tags

$str3 = preg_replace_callback('/<>/', function($matches) use (&$replacements) {
    return array_shift($replacements);
}, $str2);

echo "str1 ".$str1."<br>";
echo "str2 ".$str2."<br>";
echo "str3 ".$str3."<br>";

Upvotes: 2

Related Questions