1

Possible Duplicate:
bbcode unparser regex help

I want to convert this HTML code

<div class="postQuote"> <div class="postQuoteAuthor"><a href="http://www.siteurl.com/profile.php?user=Username">Username</a> wrote...</div> quoted text</div> comment 

to bbcode ..

[QUOTE=Username] quoted text [/QUOTE] comment

I don't want a tutorial about creating bbcode , it is already setup , i just want to know how to match and replace .. to make text compatible with the new board

Community
  • 1
  • 1
Kamal Saleh
  • 479
  • 1
  • 5
  • 20

2 Answers2

0

Well, usually people resort to preg_replace... but I prefer the lengthier stripos() process

if (($startat = stripos($html,'<div class="postQuote"'))!==false) {

  $startend = stripos($html,'</div', stripos($html,'</div', $startat)+6);

  $start_username_at = stripos($html,'<a', $startat);
  $start_username_end = stripos($html,'</a', $start_username_at);

  $start_comment_at = stripos($html,'</div', $startat)+6;
  $start_comment_end = stripos($html,'</div', $start_comment_at);

  $username = trim(strip_tags(substr($html,$start_username_at,$start_username_end-$start_username_at)));
  $comment = trim(strip_tags(substr($html,$start_comment_at,$start_username_end-$start_comment_at)));
  echo "[QUOTE=Username]".$username."[/QUOTE] ".$comment;

}
Prof
  • 2,898
  • 1
  • 21
  • 38
0
$string = '<div class="postQuote"> <div class="postQuoteAuthor"><a href="http://www.siteurl.com/profile.php?user=Username">Username</a> wrote...</div> quoted text</div> comment ';

$string = preg_replace('|^<div class="postQuote".*user=([^"]+)".+</div>([^<]+)</div>(.+)$|', '[QUOTE=$1] $2 [/QUOTE] $3', $string);

echo $string; // [QUOTE=Username] quoted text [/QUOTE] comment 
kittycat
  • 14,983
  • 9
  • 55
  • 80
  • thank you , but it don't work as required it returns 'username wrote.. quoted text comment on quote ' it doesn't return '[QUOTE=Username][/QUOTE]' – Kamal Saleh Dec 03 '12 at 07:45
  • If you run the above snippet it will return correctly. Please post the exact code that you are using that is causing the problem. – kittycat Dec 03 '12 at 13:00
  • thank you , it worked exactly after small modification '$htmlcode = preg_replace('#
    ([^<]+)
    #siU', '[QUOTE=$1] $2 [/QUOTE] $3', $htmlcode);'
    – Kamal Saleh Dec 03 '12 at 18:21
  • You example did not specify it would be on multiple lines. Also 'comment' was assumed to be part of the match if you are not using that then you need to use this version so as not to be using a backreference that does not exist. '$htmlcode = preg_replace('#
    ([^<]+)
    #siU', '[QUOTE=$1] $2 [/QUOTE]', $htmlcode);' I could have done this easier with DOM if I had known you were not needing the comment portion matched as well. I highly recommend using that instead, regex is not the ideal method to do this.
    – kittycat Dec 03 '12 at 22:15