-1

I was noticing some odd results in the output of my code that I traced back to trim(). I tested and verified my result at phptester.net (please go ahead and verify). How does the following small script give the result shown?

$x = "d1d1d1";
define("REP", "xqzxqjb1");

echo trim($x, REP); //the output is the string 'd1d1d'

//Same result if $x = 'xqzxqjb1d1d1d1xqzxqjb1' OR $x = 'd1d1d1xqzxqjb1' OR $x = 'xqzxqjb1d1d1d1';

Why isn't the output 'd1d1d1' for any of these?

2 Answers2

4

Why shouldn't it be?

trim() - Strip whitespace (or other characters) from the beginning and end of a string

trim('d1d1d1', 'xqzxqjb1');
                  ^---remove these chars from the string

x,q,z,x,q,j,b - not in string, ignore
1 - present at the END of the string, strip it:

php > echo trim('d1d1d1', "xqzxqjb1");
d1d1d
     ^---see, no 1
Marc B
  • 356,200
  • 43
  • 426
  • 500
0

Because trim will remove any number of any of those characters from the ends of a string, not (as you seem to think) the entire string.

In all cases, you end up with d1d1d because that's the central part of the string after stripping away the characters in REP.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • OK...thanks. The function I need is to trim the entire substring only from the ends, which is what I thought trim() did. Is there any built-in PHP function, not str_replace(), which removes the entire string from either end of another string? – The One and Only ChemistryBlob Jul 28 '15 at 21:36
  • @TheOneandOnlyChemistryBlob : You are probably going to want to look in to regular expressions for this. – Jerbot Jul 28 '15 at 21:37