-
-
Save miguelgisbert/7ef9ee15aa0cc1ba32ea5ed192e486c3 to your computer and use it in GitHub Desktop.
Strip or remove html tags from a string and recover or put them back again at the same position.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$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>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my first share! :) I was looking to remove all the html tags from a string to translate it properly with DeepL API (it doesn't work with html tags which have attributes, even if you use their beta html handling). So with this piece of code you can remove or strip the html tags, mark the position of the html tags with a special character, and after the translation or whatever you need to do without html tags, put them back again at the same position due to they are recovered in order.