Search code examples
phpregexescapingpreg-replacetrim

Removing white space and predefined characters in PHP


I have a variable which has data stored as a string. I want to remove all occurrences of \n and \u in the string. I have tried the usual PHP string command:

$var=trim($var) 

command to remove escape characters, but it did not work, another answer suggested the use of:

trim(preg_replace('/\s\s+/', ' ',... 

However, I still cannot get rid of the characters, is there any other way to do this?

Here is what I am doing:

$some_var=trim(preg_replace('/\s\s+/', ' ', $var));
$some_arr=preg_split("/(,|:)/",$output);
while ($i<count($arr))
print $arr[i]

EDIT1: I need to remove all escape characters, and not any particular string.

EDIT2: current output:-

'\uBLD_0000_1953\n'

I want to remove the escape characters at the beginning and end of the string. They are not a part of the actual variable

Expected output:

'BLD_0000_1953'


Solution

  • Here is the method & pattern (Demo):

    echo preg_replace("/\\\[bfnrstuv0'\"]/","",'\uBLD_0000_1953\n');
    // output: BLD_0000_1953
    

    You can expand or reduce the character class as needed.


    The most literal regex pattern for your question is: /\\\[nu]/


    Smarter still (because the characters to be removed are at the beginning and end of the string) is a non-regex solution suggested by DaGhostman Dimitrov as a comment on the question:

    echo trim('\uBLD_0000_1953\n',"\\n\u");
    // output: BLD_0000_1953