Tuesday, 20 August 2013

Conditionally Replace a specific Character in a string

Conditionally Replace a specific Character in a string

I am trying to remove the @ sign from a block of text. The problem is that
in certain cases (when at the beginning of a line, the @ sign needs to
stay.
I have succeeded by using the RegEx pattern .\@, however on when the @
sign does get removed it also removes the character preceding it.
Goal: remove all @ signs UNLESS the @ sign is the first character in the
line.
<?php
function cleanFile($text)
{
$pattern = '/.\@/';
$replacement = '%40';
$val = preg_replace($pattern, $replacement, $text);
$text = $val;
return $text;
};
$text = ' Test: test@test.com'."\n";
$text .= '@Test: Leave the leading at sign alone'."\n";
$text .= '@Test: test@test.com'."\n";
$valResult = cleanFile($text);
echo $valResult;
?>
Output:
Test: tes%40test.com
@Test: Leave the leading at sign alone
@Test: tes%40test.com

No comments:

Post a Comment