Friday, March 10, 2006

Using ltrim is not the right answer sometimes.

In a PHP application I was debugging today for a company I found them using ltrim to remove a substring from the start of a string which was producing weird results such as "tal" after invoking with "Total".

When I asked their programmer why is he using ltrim, he replied to strip out a substring from the start of the string.

His code was:

$clean=ltrim($unclean, "To");

So what's the problem? If a string starts with To such as in "ToTotal" (hypothetically), it incorrectly returns "tal" when the needed result was "Total" with just the first part of To stripped.

I've posted the correct way to strip a substring using regular expressions.
  post to

php regular expressions start of line: Removing a substring from the start of a string

When using regular expressions with PHP one must take care of a few minute details.

For instance, today I received a request to debug an application.

$patterns[0] = "/^Top/";
$replacements[0] = 'bear';
$text=" Top/Top/Top/Business/Top/Accounting/Top";
$text = preg_replace($patterns, $replacements, $text);
echo $text . "\n\n";

Can you spot the problem?

Hint: running the above produces:


Here is the solution: many people mistakenly interpret ^ as the start of the line when in fact it represents the start of the string.

Modifying the above regular expression to

$patterns[0] = "/^Top\//";
$replacements[0] = 'bear/';
#$text = preg_replace("/^(Top\/)/", '__', $text);
$text = preg_replace($patterns, $replacements, $text);
echo $text;


# bear/Top/Top/Business/Top/Accounting/Top

which was the desired solution in this problem.
  post to

eXTReMe Tracker