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 Del.icio.us

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:

Top/Top/Top/Business/Top/Accounting/Top



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="Top/Top/Top/Business/Top/Accounting/Top";
#$text = preg_replace("/^(Top\/)/", '__', $text);
$text = preg_replace($patterns, $replacements, $text);
echo $text;


produces:

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

which was the desired solution in this problem.
  post to Del.icio.us

Friday, December 02, 2005

Adding a button to toolbar in Nucleus.

Edit the file PAGEFACTORY.php

Add
$this->_jsbutton('blockquote',"blockquoteThis()",_ADD_BLOCKQUOTE_TT ." (Ctrl + Shift + Q)");

And

$this->_jsbutton('blockquote',"blockquoteThis()",'');


Upload image button-blockquote.gif to admin/images directory

Edit javascript/edit.js

function blockquoteThis() { insertAroundCaret('
','
'); }
If the toolbar is enabled, the button should start working now.
  post to Del.icio.us

Thursday, November 10, 2005

PHP Header 301 Redirect - Moved Permanently

From time to time, pages change location. At times like these, one can use PHP header function with 301 to notify website visitors that the page has moved, assuming the $location contains the new URL.

Here is how you can use PHP header 301 redirect

header ('HTTP/1.1 301 Moved Permanently');
header ('Location: '.$location);


More information about header function can be obtained at PHP.net

  post to Del.icio.us

eXTReMe Tracker