Jump to content

Converting Special Characters To Html


1internet

Recommended Posts

I have site content with special characters that came form Word. However I don't want to convert all the content to htmlentities(), because I need some elements like h1, p, a, img. How can I convert all these special characters but leave the elements when they are all contained in the same string?

Link to comment
https://forums.phpfreaks.com/topic/271560-converting-special-characters-to-html/
Share on other sites

No, then you are risking javascript being used. You need to replace specific tags only. Example:

 

<?php

// $_POST['sometext'] will be <h1>Title</h1><p>Some paragraph</p><script>alert(hi)</script>

$original_text = htmlentities($_POST['sometext']);

// The htmlentitied tags (< being <  and > being >)
$converted = array('<p>', '</p>', '<h1>', '</h1>');

// What to replace them with
$tags = array('<p>', '</p>', '<h1>', '</h1>');

// Use str_replace to make things so much simpler
$new_stuff = str_replace($converted, $tags, $original_text);

echo $new_stuff;
?>

 

$new_stuff will display Title as an h1 header and the paragraph but will convert the script tags so they won't work

Personally I prefer the following method for defining a relationship between search and replacement terms:

$replacements = array (
   '<p>' => '<p>',
   '</p>' => '</p>',
   '<h1>' => '<h1>',
   '</h1>' => '</h1>',
);

Then use array_keys () and array_values () in the str_replace () call. Makes it a lot easier to see the exact relations, and much harder to mess them up by forgetting to edit one of the arrays (or editing in the wrong place).

  On 12/4/2012 at 10:16 AM, Christian F. said:

Personally I prefer the following method for defining a relationship between search and replacement terms:

$replacements = array (
'<p>' => '<p>',
'</p>' => '</p>',
'<h1>' => '<h1>',
'</h1>' => '</h1>',
);

Then use array_keys () and array_values () in the str_replace () call. Makes it a lot easier to see the exact relations, and much harder to mess them up by forgetting to edit one of the arrays (or editing in the wrong place).

 

I only like to provide basic code (unless payed). But this seems like a much neater method.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.