Issue
For example, if I have
<b>Line 1
Line 2</b>
I want to make it become
<b>Line 1</b>
<b>Line 2</b>
thanks.
Solution
There's a simple way to go about this if you're using code, though it's generally frowned upon to use regex to parse / handle HTML or any markup language.
First of all, the pattern:
/<b>(.*?)<\/b>/s
What this will do, is capture everything (ungreedy) between <b>
and the next </b>
, including the tags.
The full match will be the entire string (to replace) and the captured group will be the text to replace it with (with a bit of modification in code).
The way to do this is to get all the matches, and then iterate each match (go from last to first), explode the captured group on \n
, then wrap each string with <b>
and </b>
before imploding it back with \n
again.
Replace the match with this resulting string. This will also handle the case where you have <b>
and </b>
on the same line already.
PHP example:
$string = <<<EOD
<b>Bold Text
Bold Text</b>
Normal Text
Normal Text
<b>Bold Text</b>
EOD;
preg_match_all("/<b>(.*?)<\/b>/s", $string, $matches, PREG_PATTERN_ORDER);
for ($match = count($matches[0]) - 1; $match >= 0; $match--) {
$replace = implode("\n", array_map(function ($str) {
return "<b>".$str."</br>";
}, explode("\n", $matches[1][$match])));
$string = str_replace($matches[0][$match], $replace, $string);
}
echo $string;
will output:
<b>Bold Text</b>
<b>Bold Text</b>
Normal Text
Normal Text
<b>Bold Text</b>
Answered By - Jamie - Fenrir Digital Ltd Answer Checked By - Marie Seifert (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.