将以下文本替换为字符串末尾的“”

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
}

Live demo