PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How can I make all html tags close in the same line with php

 November 20, 2022     dom, htmlpurifier, php, preg-replace, regex     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing