简体   繁体   中英

Removing special Characters from string

I am using a function for removing special character from strings.

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

And here is the test case

echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g

with Reference from SO Answer. The problem is what if ' is the last character in my string , Like I get a string America' from a excel file ,If I put that in this function, it wouldn't escape ' .Any help when first and last character is '

try to replace the regular expectation change

preg_replace('/[^A-Za-z0-9\-]/', '', $string);

with

preg_replace("/[^A-Za-z0-9\-\']/", '', $string);  // escape apostraphe

or

you can str_replace It is quicker and easier than preg_replace() Because it does not use regular expressions.

$text = str_replace("'", '', $string);

In a more detailed manner from Above example, Considering below is your string:

$string = '<div>This..</div> <a>is<a/> <strong>hello</strong> <i>world</i> ! هذا هو مرحبا العالم! !@#$%^&&**(*)<>?:";p[]"/.,\|`~1@#$%^&^&*(()908978867564564534423412313`1`` "Arabic Text نص عربي test 123 و,.m,............ ~~~ ٍ،]ٍْ}~ِ]ٍ}"; ';

Code:

echo preg_replace('/[^A-Za-z0-9 !@#$%^&*().]/u','', strip_tags($string));

Allows: English letters (Capital and small), 0 to 9 and characters !@#$%^&*().

Removes: All html tags, and special characters other than above

At a first glance i think that the addslashes function could be a starting point. http://php.net/manual/en/function.addslashes.php

Definitely a better pattern out there, but this should work for the entire string:

preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", '', $string);

If you need to replace them around words in the string you'll have to use \\b for word boundaries. Also, if you want to replace multiples at the start or end you'll need to add a + to those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM