2016-07-22 77 views
0

我有一個變量可以很早地追加到字符串中,但是如果符合條件,我需要用空字符串替換它(該條件只能在稍後確定在代碼中)。在字符串末尾用「」替換下面的文本

例如:

$indent = str_repeat("\t", $depth); 
$output .= "\n$indent<ul role=\"menu\">\n"; 

我現在需要更換什麼獲取附加到$output串在這裏與一個空字符串。這在其他地方完成,但我仍然可以訪問$ indent變量,所以我知道已經添加了多少「\ t」。

所以,我知道我可以使用preg_matchpreg_replace像這樣做:

if (preg_match("/\n$indent<ul role=\"menu\">\n$/", $output)) 
    $output = preg_replace("/\n$indent<ul role=\"menu\">\n$/", "", $output); 
else 
    $output .= "$indent</ul>\n"; 

但我在這裏想上的表現,如果有更好的方法來做到這一點?如果有人可以用我的確切$output提供一個新行和製表符的例子,那就太好了。

回答

1

如果您知道確切的字符串,並且您只想從$output的末尾刪除它,則使用正則表達式實際上是效率低下的,因爲它會掃描整個字符串並將其解析爲正則表達式規則。

假設我們稱之爲想要裁剪的文本$suffix。我會做:

//find length of whole output and of just the suffix 
$suffix_len = strlen($suffix); 
$output_len = strlen($output); 

//Look at the substring at the end of ouput; compare it to suffix 
if(substr($output,$output_len-$suffix_len) === $suffix){ 
    $output = substr($output,0,$output_len-$suffix_len); //crop 
} 

Live demo

+0

,看起來不錯,所有,但如何使用''/ N','/ t'時生效strlen'輸出,和/或'/ r'? –

+1

它可以工作。 'strlen('\ n \ n')'是4. – BeetleJuice

+0

非常感謝! –