Friday, 2 September 2011

PHP: 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.

No comments:

Post a Comment