Reputation: 23
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
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
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
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.$1
meaning that if it matches a :
then the $1 will mean :
.Upvotes: 7