PHP: str_replace() - ignore white space

2019-07-13 18:33发布

问题:

I have a string that is something like , ] }

I'd like to replace it with ] }

The problem is I don't know whether there will be white space between the , and the ]. There may be white space or there may be no white space. There may be tabs or there may be line breaks.

How can I replace ,<any white space here>] } to just ] } please?

回答1:

Instead of str_replace you can simply use preg_replace like as

echo preg_replace('/,\s*\]\s*}/',"] }",$string);
  • \s* \s checks for any space character that includes new line,tabs,space and * for zero or more occurence of space
  • \]\s*} this'll check for the ] brace \s* as specified above and } curly brace literally


回答2:

You can just use a regex with preg_replace.

$str = preg_replace('/,\s*(?=]\s*})/', "", $str);
  • \s* means any amount of any whitespace (\s is a shorthand for [ \t\r\n\f])
  • (?=]\s*}) the lookahead is used to check if ,\s* is followed by ]\s*}

See demo at eval.in



回答3:

Sorry this was without testing. This is an alternative of preg_replace. This will trim specified in the second parameter, \t, \n, , ,. So after trimming, you will be left with ]}

"\t" (ASCII 9 (0x09)), a tab
"\n" (ASCII 10 (0x0A)), a new line (line feed)

echo ltrim($string, ", \t\n");

if you are uncertain that there might be a carriage return, or a vertical tab in there, you can

echo ltrim(ltrim($str1, ","));

This will first trim down the comma then trim these characters , , \t, \r, \0, \x0B

Here's a demo