Friday, March 10, 2006

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

1 Comments:

At 12:12 AM, Blogger Unknown said...

Hi,Originally, websites were purely informational. Before the web was opened to the public in Web Design Cochin, educational and research institutions and goverment agencies were able to make information available to each other via text-only websites.Thanks.....

 

Post a Comment

<< Home

eXTReMe Tracker