3

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
  • 1
    use regex preg_replace('@\,[\h\s]+@', '', $string) Commented Nov 18, 2015 at 11:02

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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

2 Comments

Can you add details as to why this works, what this actually does? cheers
@martin updated answer in a more appropriate overview

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.