Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I remove special characters and spaces on a textfield using PHP

Tags:

php

I need to remove all special characters and spaces on a textfield for a form I'm building. How do I accomplish this in PHP.

like image 769
Benny Avatar asked Jun 02 '10 17:06

Benny


People also ask

How do I remove special characters and spaces from a string?

Use the replace() method to remove all special characters from a string, e.g. str. replace(/[^a-zA-Z0-9 ]/g, ''); . The replace method will return a new string that doesn't contain any special characters. Copied!

How do I remove special characters in HTML?

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


2 Answers

$specialChars = array(" ", "\r", "\n");
$replaceChars = array("", "", "");

$str = str_replace($specialChars, $replaceChars, $str);
like image 176
Stijn Leenknegt Avatar answered Oct 11 '22 18:10

Stijn Leenknegt


This really depends, I assume you are working with $_POST[] data and wish to sanitize those inputs? If so I would definitely do something like:

$var = preg_replace("/[^A-Za-z0-9]/", "", $var);

That will strip out everything other than alpha/num, you can adjust the regex to include other characters if you wish. Some great examples of commonly used regular expressions can be found at: The RegEx Library

If this isn't quite what you are looking for or have other questions let us know.

like image 44
niczak Avatar answered Oct 11 '22 20:10

niczak