2016-04-10 35 views
0

我有一個像www.host.com這樣的字符串,我需要從它開始刪除(在這種情況下爲www.),以使其僅爲host.com。有一些這樣的開始(如:m.,wap.等)。如何以有效和快速的方式做到這一點?什麼是從開始刪除字符串的最有效和最快捷的方式? (PHP微優化)

目前我使用這個代碼,但我覺得應該有一個更好/更快/更清潔的方式:

<?php 

function _without_start($val, $start) 
{ 
    if(_starts($val, $start)) 
    { 
     $len = mb_strlen($start); 
     $val = mb_substr($val, $len); 
    } 

    return $val; 
} 

function _starts($str, $needle) 
{ 
    return (mb_substr($str, 0, mb_strlen($needle)) === $needle); 
} 

/********************************************/ 

$host = 'www.host.com'; 

$remove_from_beginning = array('www.', 'wap.', 'admin.'); 
foreach($remove_from_beginning as $start) 
{ 
    $host = _without_start($host, $start); 
} 

var_dump($host); 
+0

使用'explode'和'in_array',而不是一個正則表達式。 –

回答

2

你不需要的foreach從字符串除去出頭,這將是一個更好的,

$url = preg_replace("/^(www|wap)\./si","","www.wap.com"); 
echo $url; 
0

既然你加入了正則表達式標籤,你可以使用改變在正則表達式做一個清單,並檢查對字符串,並與empty字符串替換。

正則表達式:^(www|admin|wap)\.

Regex101 Demo

1

隨着explodein_array

function _without_start($host, $prefixes) { 
    list($prefix, $remainder) = explode('.', $host, 2); 
    return in_array($prefix, $prefixes) ? $remainder : $host; 
} 

$prefixes = ['www', 'wap', 'admin']; 
$host = 'www.host.com'; 

echo _without_start($host, $prefixes); 
+0

不錯的例子;) – WebDevHere

0

如果你是爲一個regex基礎的解決方案(如標籤的人提到regex) ,這裏你去

$remove_from_beginning = array('www.', 'wap.', 'admin.'); 
$final = ""; 

foreach($remove_from_beginning as $start) 
{ 
    $final = $final . "" . substr_replace($start, '', -1) . "" . "\.|"; 
} 

$final = substr_replace($final, '', -1); 

echo preg_replace("/" . "" . "(?:" . "" . $final . "" . ")" . "" . "(.*)" . "" . "/", "$1", "www.exaple.com"); 

Ideone Demo

相關問題