Mateusz Osuch
Mateusz Osuch

Reputation: 55

PHP substr used with preg_replace

I have function:

function postNumberToLink($string) {
 return preg_replace('!\>\>\d+!', "<a href='#$0'><font color='red'>$0</font></a>", $string);
}

My questions:

"I'm replying to post no. >>21313123" to "I'm replying to post no. [href=21313123][red]>>21313123[/red][/href]" ?

Sorry for brackets[], but I can't figure out how do SO tags work.

Regards Matt

Upvotes: 1

Views: 137

Answers (1)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175038

Your Questions

  1. Keep it in your syntax in the database. This has several advantages:

    • You are not limited to HTML only. What if you make an API tomorrow that outputs JSON or XML?
    • You don't need to unparse and reparse it every time you need to edit.
  2. You can use control groups in your regular expression:

    return preg_replace('!\>\>(\d+)!', "<a href='#$1'><font color='red'>$0</font></a>", $string);
    //                        ^   ^ Brackets!     ^^ First group        ^^ All match
    

Extra Points:

  • Don't use <font> it's deprecated since before Jon Skeet had less than 100k reputation. Instead, use a class name on your links, and use CSS to style those:

    <a href="#" class="reply-to"> 
    

Upvotes: 1

Related Questions