0

I am relatively new to regular expressions. I just wanted to know that how to replace empty spaces or carriage return ( new line ) through preg_replace in php for this string:

[someshortcode]

[someshortcode]

The string has ] at the end of one line and [ at the new line. I want to remove any spaces/ characters be it '\r' ,'\t', '\n', empty spaces or any other character

output should be like this: [someshortcode][someshortcode]

Thanks

Jenz
  • 8,280
  • 7
  • 44
  • 77
Mushtaq Ali
  • 45
  • 10
  • What is your current regex? – Alma Do Apr 03 '14 at 12:38
  • 1
    possible duplicate of [how to remove new lines and returns from php string?](http://stackoverflow.com/questions/3986299/how-to-remove-new-lines-and-returns-from-php-string) – MSadura Apr 03 '14 at 12:41

1 Answers1

4
$result = preg_replace("/\s/", '', $string);

You can learn more about the "\s" and others in Escape sequences

Update:

I'd like to add an alternative with POSIX compliant regular expression, where you could use the following line, which by the way would also match the VT character (code 11):

$result = preg_replace("/[[:space:]]/", '', $string);

More about Character classes

blue
  • 1,939
  • 1
  • 11
  • 8
  • 1
    Just a notice - in his case it is job for `str_replace` as it will be faster. – MSadura Apr 03 '14 at 12:53
  • @MarkS - I do agree. Still the author explicitly asked for **preg_replace**. – blue Apr 03 '14 at 12:55
  • 1
    +1 Thanks mate for correcting me. I was in a false notion. Thanks once again. I deleted my answer ;) – Amit Joki Apr 03 '14 at 12:57
  • @blue Thanks, that's what I was looking for. However your previous answer also worked fine for me. – Mushtaq Ali Apr 03 '14 at 13:00
  • 1
    @blue May I ask, why you're using `m (PCRE_MULTILINE)`, where anchors for str start/end also match the line start/end, which arent't used here. – Jonny 5 Apr 03 '14 at 13:16
  • @Jonny5 - you're right. /m has no effect, so its presence is useless, removing. – blue Apr 03 '14 at 13:37