2016-07-22 78 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

非常感谢! –