0

Im reading in a piece of HTML text. I want to remove all HTML tags except paragraphs and headings. To do this i use str_replace to replace the tags that i want with string placeholders. Then strip the HTML tags. Then finally replace the string placeholders with the original HTML code. This is where it is failing.

$Text = 'ManyENH3 different';

$updatedText = str_replace("ENH3", "</h3>", $Text);

The above code wont remove the ENH3 string. I have tried messing around and it doesnt work when there is no space before or after the word. I tried using preg_replace and it returns a blank string.

4
  • Why you dont use strip_tags ? Commented Nov 17, 2014 at 15:43
  • or php.net/manual/en/function.strip-tags.php in english even :) Commented Nov 17, 2014 at 15:44
  • The variable name was just a typo when i added the code. Its a lot more complicated than this in my actual script i just simplified the issue Commented Nov 17, 2014 at 15:44
  • Although you should use @BenjaminPoignant's answer, what is the problem with your code? It works fine: codepad.viper-7.com/MHLzIM Commented Nov 17, 2014 at 15:52

1 Answer 1

3

You can try :

$updatedText = strip_tags($Text, '<p><h1><h2><h3><h4><h5><h6>');
Sign up to request clarification or add additional context in comments.

3 Comments

aw damn i wish i had of known this when i started this script. Unfortunately the data is now in a database. I can rewrite the script and start again from scratch processing the data, but ive already come so far i would like if i could fix the stored data
$Text = 'ManyENH3 different'; $stored_data_tag = array("ENH1","ENH2","ENH3","ENH4","ENH5","ENH6","ENP"); $real_tag = array("</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</p>"); $updatedText = str_replace($stored_data_tag, $real_tag, $Text); var_dump($updatedText);
Awesome That fixed it! thank you. Double thank you for the strip_tags information. this will be really useful for me in the future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.