creatoro
creatoro

Reputation: 23

Remove whitespace around certain character with preg_replace

I have a string where I want to remove all the whitespace around a certain character using preg_replace. In my case this character is /.

For example:

first part / second part would become first part/second part

Or let's say that character is : now:

first part : second part would become first part:second part

I couldn't find an example on how to do this... Thanks!

Upvotes: 2

Views: 3593

Answers (3)

Billy Moon
Billy Moon

Reputation: 58531

match optional space followed by your character (captured in brackets) followed by another optional space and then replace by your captured character

preg_replace('/\s*(:)\s*/',"$1",$str);

Upvotes: 1

orlp
orlp

Reputation: 117681

Replace : with your character.

$string = preg_replace("/\s*:\s*/", ":", $string);

In english:

Replace any amount of whitespace (including 0), then a : and then any amount of whitespace again, by just a :.

Upvotes: 1

Jakub Hampl
Jakub Hampl

Reputation: 40543

$string = preg_replace("/\s*([\/:])\s*/", "$1", $string);

Explanation:

  • \s* means any amount (*) of whitespace (\s)
  • [\/:] is either a / or a :. If you want another character, just add it here.
  • the brackets are a capture group which you reference with the $1 meaning that if it matches a : then the $1 will mean :.

Upvotes: 7

Related Questions