stormist
stormist

Reputation: 5905

PHP: Correct regular expression for making every letter left of the first colon lowercase

$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';

Right now I have:

$value = preg_replace('/(^.+)(?=:)/e', "strtolower('\\1')", $value);

this outputs

$value='x-cem-date:wed, 16 dec 2009 15:42:28 GMT';

it should output:

$value='x-cem-date:Wed, 16 Dec 2009 15:42:28 GMT';

Upvotes: 0

Views: 179

Answers (6)

YOU
YOU

Reputation: 123841

Just for information, this is the version using preg_replace_callback

$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';

function callback($text){return(strtolower($text[0]));}

echo preg_replace_callback("/^([^:]+:)/","callback",$value);

output

x-cem-date:Wed, 16 Dec 2009 15:42:28 GMT

Upvotes: 1

Alana Storm
Alana Storm

Reputation: 166076

Try your regular expression with a match

$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';
$value = preg_match('/(^.+)(?=:)/e', $value, $matches); 
print_r ($matches) . "\n";

This should output

Array
(
    [0] => x-Cem-Date:Wed, 16 Dec 2009 15:42
    [1] => x-Cem-Date:Wed, 16 Dec 2009 15:42
)   

Try this instead

$value='x-Cem-Date:Wed, 16 Dec 2009 15:42:28 GMT';
$value = preg_replace('/(^.+?:)/e', "strtolower('\\1')", $value);   
echo $value . "\n";

The ? is in there so the regex isn't greedy and grabbing more than it should.

Upvotes: 1

user187291
user187291

Reputation: 53940

echo preg_replace('~^[^:]+~e', 'strtolower("$0")', $value);

Upvotes: 1

Atli
Atli

Reputation: 7930

Try

preg_replace('/([\w-]+?)(:[\w\d\s\:\,]+)/e', "strtolower('\\1') . '\\2'", $value);

It works on the example you posted, at least.

Upvotes: 1

Jeff Rupert
Jeff Rupert

Reputation: 4840

Your regular expression should be as follows:

/(^.+?)(?=:)/

The difference is the +? character. The +? is non-greedy, meaning that it will find the LEAST amount of characters until the expression moves onto the next match in the expression, instead of the MOST characters until the next match.

Upvotes: 3

sakabako
sakabako

Reputation: 1150

You might consider using explode() and implode() instead of a regular expression.

$value_a = explode( ':', $value );
$value_a[0] = strtolower( $value_a[0] );
$value = implode( ':', $value_a );

Upvotes: 2

Related Questions