Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_replace_callback blockquote regex

Tags:

regex

php

I am trying to create a REGEX that will

Input

> quote
the rest of it

> another paragraph
the rest of it

And OUTPUT

quote the rest of it

another paragraph the rest of it

with a resulting HTML of

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

This is what I have below

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

DEMO

Any help or suggestion would be appreciated

like image 778
Ramazan ŞAHİN Avatar asked Jun 12 '26 09:06

Ramazan ŞAHİN


1 Answers

Here is a possible solution for the given example.

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

Outputs :

<blockquote><p>quote 
the rest of it</p><p>another paragraph
the rest of it</p></blockquote>
like image 121
Syscall Avatar answered Jun 13 '26 23:06

Syscall