Pass string in this function.

function clean($string){
   $string = str_replace(' ', '-', $string); // Replaces spaces with hyphens.
   return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

For more info, check this Remove Special Character - Stackoverflow

Answer from Nana Partykar on Stack Overflow
🌐
W3Schools
w3schools.com › php › php_string_escape.asp
PHP - Escape Characters
In PHP, an escape character is a backslash \ followed by the character you want to insert.
🌐
PHP
php.net › manual › en › regexp.reference.escape.php
PHP: Escape sequences - Manual
In UTF-8 mode, "\x{...}" is allowed, where the contents of the braces is a string of hexadecimal digits. It is interpreted as a UTF-8 character whose code number is the given hexadecimal number. The original hexadecimal escape sequence, \xhh, matches a two-byte UTF-8 character if the value is greater than 127.
Discussions

mysql - escape special character from string in php - Stack Overflow
we are trying to escape some special character from our string please tell me the function that we have to use e.g. HTC Desire 210 – White In this example we escape -(hyphen) special character. In ... More on stackoverflow.com
🌐 stackoverflow.com
PHP escape character in strings - PHP - SitePoint Forums | Web Development & Design Community
I would like to be able to type strings like so in PHP: $route = “{controller}/{action}/{id}”; And like so: $route = “\{controller\}/{action}/{id}”; Hence the escape character “\”. What annoys me however is that if I want to do the following: $route = “\{controller\}/{action}/{id}”; ... More on sitepoint.com
🌐 sitepoint.com
0
August 20, 2014
Escape string with PHP and HTML - Stack Overflow
would be more correct. On the second one, you're escaping the ' quotes, which means that you never terminate the string, meaning that the . $type . portion is treated as plaintext within the string, not a PHP concatenation operation. More on stackoverflow.com
🌐 stackoverflow.com
How to interpret escape characters in the browser?
HTML special characters doesn't convert text line breaks (\n) to
tags. It is mainly concerned with quotes, ampersands, and other special characters. https://www.php.net/manual/en/function.htmlspecialchars.php Note: There is no tag for a tab (\t) in HTML. In this case, you probably don't htmlspecialcharacters(). It is useful because it can prevent Javascript from being output to the page. Imagine some text like this: "". What is looks like you have is a tab separated CSV file. https://www.php.net/manual/en/function.fgetcsv.php Each line will be broken up into a list of items. You can use array_map() to apply htmlspecialcharacters() to each printable item in the list. Then you can combine all the list items into a string with implode(). $order = fgetcsv($fp, 1000, "\t"); $order = array_map('htmlspecialchars', $order); echo implode(" ", $order) . "
"; This is one way of doing this if you want to avoid Javascript injection. More on reddit.com
🌐 r/PHPhelp
3
1
April 4, 2022
People also ask

Why do we use escape characters in PHP?
We use escape characters to avoid errors when a string includes symbols like quotes, tabs, or backslashes. Without them, PHP might end the string early or misread the input.
🌐
flatcoding.com
flatcoding.com › home › php escape characters: how to escape special characters
PHP Escape Characters: How to Escape Special Characters - FlatCoding
What are the most common escape characters in PHP?
  • \n – new line
  • \t – tab space
  • \\ – backslash
  • \" – double quote
  • \' – single quote (only in single-quoted strings)
🌐
flatcoding.com
flatcoding.com › home › php escape characters: how to escape special characters
PHP Escape Characters: How to Escape Special Characters - FlatCoding
How do I escape double quotes in PHP?
Use \" inside double-quoted strings. For example:
echo "She said, \"Hello\"";
🌐
flatcoding.com
flatcoding.com › home › php escape characters: how to escape special characters
PHP Escape Characters: How to Escape Special Characters - FlatCoding
🌐
TinyMCE
tiny.cloud › blog › php-escape
How to work with PHP escape quotes and characters | TinyMCE
December 7, 2023 - This function returns a list of each instance of a single character, and allows you to replace that with an escaped character. Useful for finding and replacing multiple special characters at once. ... This function is more effective for handling content that could fit into the JSON key and value structure. It creates a JSON data structure out of the content, which avoids the errors found in PHP when escaping quotes altogether.
🌐
MojoAuth
mojoauth.com › escaping › php-string-escaping-in-php
PHP String Escaping in PHP | Escaping Methods in Programming Languages
Here are some common special characters that can be escaped: Single Quote: \' – Used within single-quoted strings. Double Quote: \" – Used within double-quoted strings. Backslash: \ – Escapes the backslash itself.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-use-escape-characters-in-php
How to use Escape Characters in PHP ? - GeeksforGeeks
July 12, 2024 - Heredoc syntax allows the inclusion of escape characters and variable interpolation within a multi-line string. ... <?php $variable = "example"; $heredocString = <<<EOD This is an "example" of a Heredoc string. It can include newlines \n and tabs \t.
🌐
SitePoint
sitepoint.com › php
PHP escape character in strings - PHP - SitePoint Forums | Web Development & Design Community
August 20, 2014 - I would like to be able to type strings like so in PHP: $route = “{controller}/{action}/{id}”; And like so: $route = “\{controller\}/{action}/{id}”; Hence the escape character “\”. What annoys me however is that if I want to do the following: $route = “\{controller\}/{action}/{id}”; PHP automatically converts this to: $route = “{controller}/{action}/{id}”; Despite the { and } symbols having no special meaning in PHP.
Top answer
1 of 3
3

Example 1: Variable between single quotes

If you use single quotes everything between them will always be treated as part of the string.

$output .= '<div class="tab-pane" id="' . $type . '">";

Example 2: Variable between double quotes (option 1)

If you have a variable that you want to pass in a string you can just put it in there if you use double quotes and de variable is nog 'touching' the other words. It should always have spaces.

$output .= "<p>i would like to $your_text_here with you.</p>";

Example 3: Escaping quotes in a string

Escaping characters in a string can be done by using a \ (backslash) before the character you want to escape.

$output .= "<div class=\"tab-pane\" id=\"example-id\">";

Example 4: Variable between double quotes without spaces next to it

You can place your variable between {} braces if you use double quotes (option 2)

$output .= "<div class=\"tab-pane\" id=\"{$type}\">";

This question was however already answered in Mixing PHP variable with string literal

2 of 3
2

Your first block is doing string replacements, but then you use the ORIGINAL string, not the replaced one:

$output .= '<div class="tab-pane" id="' . $functionName . '">';

would be more correct. On the second one, you're escaping the ' quotes, which means that you never terminate the string, meaning that the . $type . portion is treated as plaintext within the string, not a PHP concatenation operation. Try

$output .= '<div class="tab-pane" id="' . $type . '">';

instead. note the LACK of backslash escapes.

And of course, you could use a HEREDOC, eliminating any need to escape quotes entirely:

$output .= <<<EOL
<div class="tab-pane" id="{$functioName}">
EOL;
🌐
FlatCoding
flatcoding.com › home › php escape characters: how to escape special characters
PHP Escape Characters: How to Escape Special Characters - FlatCoding
April 25, 2025 - The htmlspecialchars() and htmlentities() help escape special characters before sending the text to a web page. This prevents HTML code or scripts from running, which protects your site from attacks like cross-site scripting (XSS). ...
🌐
Reddit
reddit.com › r/phphelp › how to interpret escape characters in the browser?
r/PHPhelp on Reddit: How to interpret escape characters in the browser?
April 4, 2022 -

I'm working through the PHP and MySQL Web Development (5th Edition) and am trying to display a plain text file in the browser but am unable to interpret escape characters such as \t and \n. They show up in the output although I'd like for them to be interpreted as tabs and newlines, respectively.

Code:

<?php
  $document_root = $_SERVER['DOCUMENT_ROOT'];
?>
<!DOCTYPE html>
<html>
  <head>
    <title>Bob's Auto Parts - Customer Orders</title>
  </head>
  <body>
    <h1>Bob's Auto Parts</h1>
    <h2>Customer Orders</h2> 
    <?php
      @$fp = fopen("$document_root/../orders/orders.txt", 'rb');
      flock($fp, LOCK_SH);

      if (!$fp) {
        echo "<p><strong>No orders pending.<br />
              Please try again later.</strong></p>";
        exit;
      }

      while (!feof($fp)) {
         $order = fgets($fp);
         echo htmlspecialchars($order)."<br />";
      }

      flock($fp, LOCK_UN);
      fclose($fp); 
    ?>
  </body>
</html>

Expected output:

2 tires 2 oil 2 spark plugs Address 1
2 tires 4 oil 6 spark plugs Address 2

Actual output (same as the literal plain text file):

2 tires\t2 oil\t2 spark plugs\tAddress 1\n2 tires\t4 oil\t6 spark plugs\tAddress 2\n

I must be missing something seemingly trivial, although I'm following the book's code to the letter.

Any help would be greatly appreciated. Thank You!

🌐
JSON Formatter
jsonformatter.org › json-parser
JSON Parser Online to parse JSON
Validate JSON using PHP · Python Load Json From File · JSON.Parse() is javascript method for parsing JSON which converts to JavaScript objects. Here is the Syntax · JSON.parse(text) JSON.parse(text, reviver) Example · let jsObj = JSON.parse( '{"name":"Geico", "founded":1936, "country": "United States"}'); JSON.parse() method compatible in all browsers including IE 10.
🌐
Somacon
somacon.com › p568.php
Count Duplicates in a List Online Tool
Both TAB and CSV output are in Excel-compatible format, with double-quote as the enclosure and escape character.
🌐
Brj
en.php.brj.cz › escaping-characters-in-a-string-in-php
Escaping characters in a string in PHP
Escaping is used to write characters that have different meanings in different contexts.
🌐
Alibaba Cloud
topic.alibabacloud.com › a › font-colorredphpfont-character-font-colorredescapefont-function-summary-font-colorredescapefont-strings-font-colorredinfont-font-colorredphpfont_1_34_32439221.html
PHP character escape Function Summary (Escape strings in PHP)
December 8, 2018 - Configurations and functions related to PhP string escaping are as follows: 1. magic_quotes_runtime 2. magic_quotes_gpc 3. addslashes () and stripslashes () 4. mysql_escape_string () 5. addcslashes () and stripcslashes () 6. htmlentities () and html_entity_decode () 7. htmlspecialchars () and htmlspecialchars_decode () When magic_quotes_runtime is enabled, most PHP functions automatically add a backslash to overflow characters (including database or file) data introduced from the outside.
🌐
Gchamirpur
gchamirpur.org › pdf › lectures5 › Lecture-4-Escape-Sequences-in-PHP.pdf pdf
PHP Programming COMP203TH Lecture: 4 Escape Sequences in PHP
A line feed character · \t · A tab · \r · A carriage return · \” · A double quotation mark · \’ · A single quotation mark · When the parser encounters one of these escape sequences, it known to · replace it with the corresponding value before sending it to the output device. Example: <?php ·
🌐
Reddit
reddit.com › r/phphelp › php is adding escape characters to my json string and i have no idea why,
r/PHPhelp on Reddit: PHP is adding escape characters to my JSON string and I have no idea why,
April 18, 2023 -

I have a website that lets the user build a dynamic form (think tabs with widgets) and then reduce the whole thing to a string with json.stringify().

But when I pass it to PHP (on one of our two systems to make things weirder) it adds a mess of escape characters. For example:

  {\\"tab_type\\":\\"accordion\\",\\"options\\"{\\"tab::style\\":\\"color:0x8000ff00\\",  

When the correct formatting should look like:

 "type":"accordion","options":{"tab::style":"color:0x8000ff00" 

The json is stringified properly on the JS side but it adds the slashes as soon as I look at the variable in the GET/POST on the PHP side.

🌐
JSONLint
jsonlint.com
JSONLint - The JSON Validator
"Offensive" characters in a string need to be escaped using the backslash character \
🌐
SSOJet
ssojet.com › escaping › unicode-escaping-in-php
Unicode Escaping in PHP | Escaping Techniques in Programming
PHP makes it straightforward to embed Unicode characters directly within double-quoted strings using the \u{XXXX} escape sequence, where XXXX represents the hexadecimal Unicode codepoint.
🌐
FanFiction.net
fanfiction.net › s › 14560195 › 1 › Defiant-in-a-collar
Defiant in a collar Chapter 1: Collared, a star wars fanfic | FanFiction
Leia kept her gaze lowered, but her mind raced. This bounty hunter—Sten Warr—had just upended everything. The chains bit into her wrists as she shifted subtly, calculating. Escape routes, weapons within reach, the weight of the sharp peeling knife stolen from the kitchens still hidden in ...