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
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

Edited by SocialCloud
Link to comment
Share on other sites

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).

Edited by Christian F.
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.