Reputation: 328
Using PHP 7.2.8
I have a strange situation regarding the trim()
function in PHP. To exemplify, lets say I make this statement:
echo trim("sacas",",\s");
I get
aca
as a result. Further, if I make a slightly different call:
echo trim(" sacas",",\s")
I get
saca
(if it's hard to see, the leading spaces are still there).
As best as I can tell, what is happening is that trim
, which removes all leading and trailing characters that match a specified set, is removing all s
characters, and ignoring whitespace. However /s
is supposed to represent whitespace characters, and not match s
at all.
Any ideas why this is happening? And if so, how can I remove the whitespace while leaving the s
characters?
As a note, my problem requires that I trim both commas AND whitespace out, so I can't simply just use trim() with no extra arguments, which does leave s
alone
Upvotes: 1
Views: 184
Reputation: 13667
trim()
accepts a a list of stripped characters – not a group, or regex.
So writing sacas
means ,
s
, a
, c
, a
, and s
.
I think you’re looking for preg_replace:
preg_replace('/,\s/', '', 'sacas')
Edit: From Peter’s comment, maybe something like this:
preg_replace('/^(,|\s)+|(,|\s)+$/', '', 'sacas')
Upvotes: 3
Reputation: 1605
"As a note, my problem requires that I trim both commas AND whitespace out, so I can't simply just use trim() with no extra arguments, which does leave s alone"
This only removes leading and trailing whitespace and commas.
echo trim(" sacas, ",", ");
returns
sacas
Upvotes: 0
Reputation: 5769
You must specify all the characters you want to strip (that is, you cannot use regular expression). So, to trim whitespaces and commas, you need:
echo trim(" sacas", ", \t\n\r\0\x0B");
Upvotes: 5
Reputation: 111239
To remove leading and trailing commas and spaces, you need to use " ,"
:
echo trim(" , asd, asd, , ,", " ,");
// output: asd, asd
If you need to include more types of whitespace (tab, new line, form feed) you need to include them in the string, for example " ,\t\n\r\0\x0B"
Upvotes: 0