Php 如何使用正则表达式将HTML转换为bbcode?

Php 如何使用正则表达式将HTML转换为bbcode?,php,regex,preg-replace,preg-match,bbcode,Php,Regex,Preg Replace,Preg Match,Bbcode,可能重复: 我想转换这个HTML代码 <div class="postQuote"> <div class="postQuoteAuthor"><a href="http://www.siteurl.com/profile.php?user=Username">Username</a> wrote...</div> quoted text</div> comment 我不想要关于创建bbcode的教程,它已经设置好了,

可能重复:

我想转换这个HTML代码

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

我不想要关于创建bbcode的教程,它已经设置好了,我只想知道如何匹配和替换。。为了使文本与新板兼容,通常人们会使用preg\u replace。。。但我更喜欢更长的stripos流程

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;

}

这是未经测试的,写得很快,如果它不起作用或者你想让我解释一下,请告诉我。现在它已经被编辑和测试过了:对不起,HTML+regex的通常答案是“不”。这工作用的工具不对。如何使用锤子将汽车改装成卡车?@Johnsyweb Chuck Norris can:谢谢,但它不能按要求工作,它返回'siteurl.com/profile.php?user=username>username。。引用“它不返回”[quote=Username][/quote]“上的引用文本注释如果运行上述代码段,它将正确返回。请发布您正在使用的导致问题的确切代码。谢谢,它在小修改“$htmlcode=preg_replace”后完全有效。您的示例没有指定它将在多行上。此外,“注释”被认为是匹配的一部分,如果您不使用该注释,则需要使用此版本,以免使用不存在的反向引用。”$htmlcode=preg_replace'
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;

}
$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