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

时间:2016-07-22 04:25:57

标签: php regex preg-replace preg-match

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

例如:

$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 个答案:

答案 0 :(得分: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

相关问题