This is how it can be done, in several lines:
// $str represents string that needs cleaning:
$str = " String with line\nbreak and too much spaces ";
// Clean string with preg_replace():
$str = preg_replace('/[\x00-\x09\x0B-\x1F\x7F]|^ +| +$/', '', $str);
$str = preg_replace('/\x0A| +/', ' ', $str);
echo $str;
// Output:
"String with line break and too much spaces"
My quoestion focuses in combining two preg_replace() lines into one preg_replace() that does exactly same job.
Is that possible and if it is how it should be done?
There is many different uses for that behavior, one that I am after is defining regexp as constant or variable and use that within class function to clean up and validate user input.
Simplified example of suchs class:
class cleaner{
protected $defined_methods = array(
'TRIM' => '/ +/',
'STRIP_CC' => '/[\x00-\x1F\x7F]/',
'TRIM_STRIP_CC' => array('/[\x00-\x1F\x7F]/', '/ +/')
);
protected $defined_results = array(
'TRIM' => ' ',
'STRIP_CC' => '',
'TRIM_STRIP_CC' => array('', ' ')
);
function clean(array $input, array $methods){
foreach ($input as $key => $data){
$input[$key] = preg_replace($defined_methods[$methods[$key]], $defined_results[$methods[$key]], $data);
}
return $input;
}
}
This way validation method (regexp) can vary with input data if needed so.
See
preg_replace, it supports multiple replacements after each other.