php trim(), work poorly

主宰稳场 提交于 2019-12-11 23:06:09

问题


I need cut from page url www. using php trim() function. But this function cut and first letter, why?

$domain = parse_url('http://wordpresas.com/page/1');
$domain['host'] = trim($domain['host'], 'www.');
pr($domain['host']); //ordpresas.com

回答1:


As other have stated the second parameter of trim() contains a list of characters which get trimmed.

However you can use preg_replace() for this. This will make sure only www. will be stripped if the string starts with it.

preg_replace('/^www./', '', $domain['host']);



回答2:


The most effective way to do this is probably:

if( strncmp( 'www.', $domain['host'], 4) == 0){
    $domain['host'] = substr( $domain['host'], 4);
}

It should have complexity O(1) :)



来源:https://stackoverflow.com/questions/9127711/php-trim-work-poorly

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