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

徘徊边缘 提交于 2020-01-17 07:47:29

问题


$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';

回答1:


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.




回答2:


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 );



回答3:


Try

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

It works on the example you posted, at least.




回答4:


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



回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/1915615/php-correct-regular-expression-for-making-every-letter-left-of-the-first-colon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!