我已经挣扎了几个小时
我需要转换此字符串
"> example quote /n"
到这个
<blockquote> example quote /n </blockquote>
所以,如果我有一个以上的引用&#34;&gt;&#34;像这样
">> example quote /n"
看起来像这样
< blockquote>< blockquote>example quote < /blockquote >< /blockquote > <br>
另一个例子是:
&#34;&gt;&gt;这是一个很棒的字符串/ n&gt;下一个引用&#34;
< blockquote>< blockquote> this is a great string < /blockquote >< /blockquote > <br>
< blockquote> next quote < /blockquote >
这是我目前的代码
// plain comment
$text = "> we are here /n";
// explode into array
$single_quotes = explode("/n", $text);
$renderedHtml = "";
$quoteopeners = "";
$quoteclosers = "";
//make blockquote out of it
foreach($single_quotes as $quote)
{
$number_of_quotes = substr_count($quote,'>');
for($i = 0; $i < $number_of_quotes; $i++)
{
$quoteopeners.= '<blockquote>';
$quoteclosers.='</blockquote>';
}
//replace all the '>' with spaces
$quote = str_replace('>','', $quote);
$quote = str_replace('/n','', $quote);
$renderedHtml.= $quoteopeners.$quote.$quoteclosers;
}
出于某种原因我打字时 &#34;&GT;我们在这里/ n&#34;
它在结尾处呈现这些随机引用
<blockquote> we are here </blockquote><blockquote></blockquote>
如果你对这个问题有一个全新的解决方案,那也没关系
答案 0 :(得分:1)
$ quoteopeners和$ quoteclosers未正确初始化。试试这个:
<?php
// plain comment
$text = ">> we are here /n";
// explode into array
$single_quotes = explode("/n", $text);
$renderedHtml = "";
//make blockquote out of it
foreach($single_quotes as $quote)
{
$number_of_quotes = substr_count($quote,'>');
$quoteopeners = "";
$quoteclosers = "";
for($i = 0; $i < $number_of_quotes; $i++)
{
$quoteopeners.= '<blockquote>';
$quoteclosers.='</blockquote>';
}
//replace all the '>' with spaces
$quote = str_replace('>','', $quote);
$quote = str_replace('/n','', $quote);
$renderedHtml.= $quoteopeners.$quote.$quoteclosers;
}
echo $renderedHtml;
?>
答案 1 :(得分:0)
您可以使用preg_replace_callback()
来完成此操作
<?php
$str = preg_replace_callback(
'/^(\>+) (\w+(\s+\w+)*)/',
function ($matches) {
return str_repeat("<blockquote>", strlen($matches[1])) . $matches[2] . str_repeat("</blockquote>", strlen($matches[1]));
}, $string);
echo $str;
例如;
//Output: <blockquote>This is a simple quote</blockquote>
$string = "> This is a simple quote";
//Output: <blockquote><blockquote>This is a simple quote</blockquote></blockquote>
$string = ">> This is a simple quote";
有用的网站