将以下文本替换为“";在字符串的末尾


replace the following text with "" at the end of string

我有一个变量,它很早就被附加到字符串中,但如果满足某个条件,我需要用空字符串替换它(该条件只能在稍后的代码中确定)。

例如:

$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的例子,其中包含换行符和制表符,那就太好了。

如果您知道确切的字符串,并且只想将其从$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
}

实时演示