Given a string which contains printable and not-printable characters. The task is to remove all non-printable characters from the string. Space ( ) is first printable char and tilde (~) is last printable ASCII characters. So the task is to replace all characters which do fall in that range means to take only those char which occur in range(32-127). This task is done by only different type regex expression.
Example:
Input: str = "\n\nGeeks \n\n\n\tfor Geeks\n\t"
Output: Geeks for Geeks
Note: Newline (\n) and tab (\t) are commands not printable character.
Method 1: Using general regular expression: There are many regex available. The best solution is to strip all non-ASCII characters from the input string, that can be done with this preg_replace.
Example:
php
<?PHP
$str = "Geeks šž for ÂGee\tks\n";
$str = preg_replace( '/[\x00-\x1F\x80-\xFF]/' , '' , $str );
echo ( $str );
?>
|
Method 2: Use the ‘print’ regex: Other possible solution is to use the print regular expression. The [:print:] regular expression stands for “any printable character”.
Example:
php
<?PHP
$str = "Geeks šž for ÂGee\tks\n";
$str = preg_replace( '/[[:^print:]]/' , '' , $str );
echo ( $str );
?>
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 May, 2023
Like Article
Save Article