1

What's the fastest way to insert a string before the </a> tag?

<a href="..."> bla bla... </a>
David
  • 208,112
  • 36
  • 198
  • 279
Alex
  • 66,732
  • 177
  • 439
  • 641

3 Answers3

3
str_replace("</a>", "blabla</a>", $text);
code_burgar
  • 12,025
  • 4
  • 35
  • 53
  • is this faster than preg_replace? – Alex Dec 03 '10 at 21:31
  • Yeah, because there is no attempts to parse the (nonexistent in this case) regular expression. – code_burgar Dec 03 '10 at 21:32
  • @Alex: Why do you care? Is this code going to run millions of times per second? Isn't it more important for you to find a solution that always works, rather than one that works most of the time but is faster? – Mark Byers Dec 03 '10 at 21:32
  • no, it's just for a menu with 30-40 links, but it doesn't hurt to use the fastest method for this :) – Alex Dec 03 '10 at 21:34
  • @Mark Byers: are you suggesting that somehow str_replace("", "blabla", $text) would be less reliable than preg_replace("", "blabla", $text)? – code_burgar Dec 03 '10 at 21:36
  • @code_burgar: No, I think both suggestions have the same problem (they both don't work in edge cases). I'm just wondering why the OP thinks speed is more important than correctness. And why this is even a sensible question to ask in the first place... seems like a bad design IMHO, but I could be wrong... there may be a sensible reason to do this, I just can't think of it. – Mark Byers Dec 03 '10 at 21:43
1

There are many, many ways to skin this cat, but here are a few common ones:

IN HTML:

<a href=""><?php echo $foo; ?></a>
<a href=""><?=$foo?></a>

IN PHP

echo "<a href=\"\">$foo</a>";
echo "<a href=\"\">{$foo}</a>";
echo "<a href=\"\">". $foo ."</a>";

Edit, you said "fastest", which I overlooked

Assuming we are talking about PHP, specifically: Supposedly using the comma for string concatenation in php is one of the fastest ways to build a string. But unless you are doing this an awful lot, this seems like an optimization that won't buy you very much.

echo "<a href=\"\">", $foo ,"</a>";
sfrench
  • 910
  • 5
  • 9
0

<a href="..."> bla bla... <?php echo "string"; ?></a>

brett
  • 191
  • 4