php preg_replace_callback block 引用正则表达式

标签 php regex

我正在尝试创建一个 REGEX

输入

> quote
the rest of it

> another paragraph
the rest of it

OUTPUT

quote the rest of it

another paragraph the rest of it

生成的 HTML

<blockquote>
<p>quote
the rest of it</p>
<p>another paragraph
the rest of it</p>
</blockquote>

下面是我的

$text = preg_replace_callback('/^>(.*)(...)$/m',function($matches){
    return '<blockquote>'.$matches[1].'</blockquote>';
},$text);

DEMO

如有任何帮助或建议,我们将不胜感激

最佳答案

这是给定示例的可能解决方案。

$text = "> quote
the rest of it

> another paragraph
the rest of it";


preg_match_all('/^>([\w\s]+)/m', $text, $matches);

$out = $text ;
if (!empty($matches)) {
    $out = '<blockquote>';
    foreach ($matches[1] as $match) {
        $out .= '<p>'.trim($match).'</p>';
    }
    $out .= '</blockquote>';
}

echo $out ;

输出:

<blockquote><p>quote 
the rest of it</p><p>another paragraph
the rest of it</p></blockquote>

关于php preg_replace_callback block 引用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48845414/

相关文章:

javascript - 如何以表格格式发送带有数据的邮件

JAVA - 正则表达式 : Unclosed Character Class

regex - 如何将COUNTIF与OR结合

正则表达式:提取字符串中两个标签之间的子字符串

php - 在 var/www/html 中部署 Laravel

php - laravel action() 辅助方法中的欺骗请求方法?

javascript - 使用PHP复制div并随机化

java - 为什么 "\r\n".split ("\r\n") 返回一个空数组?

Javascript:正则表达式 polyfill 到 IE 中的 'y' 标志

php - 两个日期之间的SQL存储逻辑