PHP str_replace slash and quote - php

I had my data called from db with words contained ' such as company's and some words display like company\\\\\'s, despite I had a function to replaced all those special characters into normal, but wording like company\'s is still around. Is there any proper way to replace all kind of special characters properly?
function chrEncode($data) {
$data = str_replace('’', ''' ,$data);
$data = str_replace('é', 'é' ,$data);
$data = str_replace('â€', '-' ,$data);
$data = str_replace('-œ', '"' ,$data);
$data = str_replace('“', '"' ,$data);
$data = str_replace('ê', 'ê' ,$data);
$data = str_replace('ö', 'ö' ,$data);
$data = str_replace('…', '...' ,$data);
$data = str_replace('-¦', '...' ,$data);
$data = str_replace('–', '–' ,$data);
$data = str_replace('′s', '’' ,$data);
$data = str_replace('-²s', '’' ,$data);
$data = str_replace('‘', ''' ,$data);
$data = str_replace('-˜', ''' ,$data);
$data = str_replace('-“', '-' ,$data);
$data = str_replace('è', 'è' ,$data);
$data = str_replace('(', '(' ,$data);
$data = str_replace(')', ')' ,$data);
$data = str_replace('•', '•' ,$data);
$data = str_replace('-¢', '•' ,$data);
$data = str_replace('§', '•' ,$data);
$data = str_replace('®', '®' ,$data);
$data = str_replace('â„¢', '™' ,$data);
$data = str_replace('ñ', 'ñ' ,$data);
$data = str_replace('Å‘s', 'ő' ,$data);
$data = str_replace('\\\"', '"' ,$data);
$data = str_replace("\r", '<br>' ,$data);
$data = str_replace("\\r", '<br>' ,$data);
$data = str_replace("\n", '<br>' ,$data);
$data = str_replace("\\n", '<br>' ,$data);
$data = str_replace("\\\'", '&#39' ,$data);
$data = str_replace("'", "&#39" ,$data);
return $data;
}
Please advise, thanks!

There is a inbuilt php function stripslashes
echo stripslashes($data);

You can remove all special character by using preg_replace like this:
preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
or only for slashes:
$str = 'h///e/ll\\o\\//\\';
str_replace(array('\\', '/'), '', $str); // output hello
Another solution:- create a clean function
function clean($string) {
$string = str_replace('', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
Usage:-
echo clean('a|"bc!#£de^&$f g');
Will output: abcdef-g

This are the special characters You need to escape them with extra backslash like this
str_replace("\\","", $data);

stripslashes is needed to get rid off the slashes...
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);

You can use mysql_real_escape_string() function when insert or update, and you will not have to replace special chars like ', quot, etc.

Related

Laravel string replace item

How to i replace '[' charachter to span class = "someclass" .I wrote this code but it gives me only text
$replaced = str_replace(
array('[', ']'),
array("<span class"."='innovation_color innovation_color-services".">","</"."span".">"),
$string
);
you are missing some quotes :
$replaced = str_replace(
['[', ']'],
["<span class"."='innovation_color innovation_color-services'".">","</"."span".">",
$string
);

str_replace() doesn't work using "(" and "[" PHP

This is my simple code function in php
function replaceCharact($input,$action){
$output_1 = str_replace('(', "%11%", $input);
$output_2 = str_replace(')', '%12%', $output_1);
$output_3 = str_replace('[', '%13%', $output_2);
$output_4 = str_replace(']', '%14%', $output_3);
$output_5 = str_replace('"', '%15%', $output_4);
$output_6 = str_replace('/', '%16%', $output_5);
$output_7 = str_replace('"\"', '%17%', $output_6);
$output_8 = str_replace('!', '%18%', $output_7);
$output_9 = str_replace('<', '%19%', $output_8);
$output_10 = str_replace('>', '%20%', $output_9);
return $output_10;
}
Only the "!"($output_8) change to %19%. The others output display nothing. Can you help me with this?
To simplify mass replacements using an array, try this...
$replacement = array(
'(' => "%11%",
')' => '%12%',
'[' => '%13%',
']' => '%14%'
// etc etc
);
$string = str_replace( array_keys( $replacement ), $replacement, $string );
https://3v4l.org/kmXZp

Special characters showing invalid

I am using a way to compress HTML on fly. Below is the function
function compress_page($buffer) {
$search = array(
'/\>[^\S ]+/s', /*strip whitespaces after tags, except space*/
'/[^\S ]+\</s', /*strip whitespaces before tags, except space*/
'/(\s)+/s', /*shorten multiple whitespace sequences*/
);
$replace = array(
'>',
'<',
'\\1',
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
function is working but the problem is, after implement this, germam characters are not showing anymore. They are showing like "�". Can you please help me to find problem.
I tried other ways to minify HTML but get same proble.
Maybe it's happen because you are not add Unicode flag support to regex.
Anyway I write a code to minified:
function sanitize_output($buffer, $type = null) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/', // Remove HTML comments
'#/\*(.|\s)*\*/#Uu' // Remove JS comments
);
$replace = array(
'>',
'<',
' ',
'',
''
);
if( $type == 'html' ){
// Remove quets of attributs
$search[] = '#(\w+=)(?:"|\')((\S|\.|\-|/|_|\(|\)|\w){1,8})(?:"|\')#u';
$replace[] = '$1$2';
// Remove spaces beetween tags
$search[] = '#(>)\s+(<)#mu';
$replace[] = '$1$2';
}
$buffer = str_replace( PHP_EOL, '', preg_replace( $search, $replace, $buffer ) );
return $buffer;
}
After research, I found this solution. This will minify full html in one line.
function pt_html_minyfy_finish( $html ) {
$html = preg_replace('/<!--(?!s*(?:[if [^]]+]|!|>))(?:(?!-->).)*-->/s', '', $html);
$html = str_replace(array("\r\n", "\r", "\n", "\t"), '', $html);
while ( stristr($html, ' '))
$html = str_replace(' ', ' ', $html);
return $html;
}
Hope this will help someone!

Preg_replace &, ; and #

I am using following PHP code to escape user input however &,# and ; can not be escaped since these are also used in the codes of other special characters. Here is my code
>$data = preg_replace("/</", "<", $data);
>$data = preg_replace("/>/", ">", $data);
>$data = preg_replace("/\"/", """, $data);
>$data = preg_replace("/\(/", "(", $data);
>$data = preg_replace("/\)/", ")", $data);
>$data = preg_replace("/'/", "'", $data);
>$data = preg_replace("/{/", "{", $data);
>$data = preg_replace("/}/", "}", $data);
>$data = preg_replace("/\`/", "`", $data);//tick mark
>$data = preg_replace("/\[/", "[", $data);
>$data = preg_replace("/\]/", "]", $data);
>$data = preg_replace("/\=/", "=", $data);
SO can you tell me how to escape &, # and ; with out disturbing rest of the code. Am sure this must have been asked many times to if u can direct me to relevant post. Also if some firend has created his own code / module / class for escaping that will be really cool
You better should use htmlentites(), which will do all work for you :
$data = htmlentities($data, ENT_QUOTES);
Documentations here

Delete special char \

How can i delete a html-special char \ from a string.
$string = 'This is \ a string with \ special characters \';
str_replace("char_to_rep","",$string); // replacing with nothing means deleting
also ref.
how-to-remove-html-special-chars
str_replace("#"," ",$string)
try this code for all special char
use str_replace and replace special char with an empty character
thanks a lot for help, but is there a better way tho do this below?
$post = '(&repl^eac&e_+';
function repleace($post) {
$array = array('.html', '.php', '±', '§', '!', '#', '€', '`', '#', '$', '%', '^', '&', '*', '(', ')', '+', '=', '<', '>', '?', '/', '|', '[', ']', ':', ';', ',', '~', '.');
$post = str_replace($array, '', $post);
$post = str_replace(' ', '_', $post);
$post = str_replace('-', '_', $post);
return strtolower('/'.$post.'/');
}
function($input) {
$input = preg_replace("/&#?[a-z0-9]{2,8};/i","",$input);
$input = ucfirst($input);
return $input;
}
The php pre_repleace function within the /&#?[a-z0-9]{2,8};/i characters works fine.

Categories