Reputation: 6217
I have a variable that gets appended to a string early, but I need to replace it with an empty string if a condition is met (that condition can only be determined later on in the code).
For example:
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<ul role=\"menu\">\n";
I now need to replace what gets appended to the $output
string here with an empty string. This gets done elsewhere, but I still have access to the $indent variable, so I know how many "\t" has been added.
So, I know I can do it using preg_match
and preg_replace
like so:
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";
But I am wondering on the performance here, and if there is a better way to do this? If someone can provide an example using my exact $output
with newline and tab characters, that would be great.
Upvotes: 0
Views: 46
Reputation: 40896
If you know the exact string, and you only want to remove it from the end of $output
, using a regular expressions is really inefficient because it scans the whole string and parses it for regex rules.
Suppose we call the text you wish to crop $suffix
. I would do:
//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
}
Upvotes: 1