Home > front end >  Regexp for fix broken HTML tags
Regexp for fix broken HTML tags

Time:01-20

I have broken HTML tags like:

$page = "some text <p/ another text <br/ some text <br/ and/or another text";

and I need to fix it to normal <br> <p>

I'm trying this: $page = preg_replace('/(\<(. ?)\/)/i', '<\2>', $page);

but it's not works

I used name "tag" for group 2: $page = preg_replace('/(\<(?<tag>. ?)\/)/i', '\k<tag>', $page);

but it is not works too.

Where I'm wrong? Help me please.

I simplified the example for clarity in the form of html. In fact, there are not only tags present there, there are words such as the names of cities, streets and other data, and all of them cannot be provided for a simple replacement

I checked it here. It seems ok, but on php I have no result https://regex101.com/r/t1JmJP/1

CodePudding user response:

Your initial code works fine:

<?php

$page = "some text <p/ another text <br/ some text <br/ and/or another text";
$page = preg_replace('/(\<(. ?)\/)/i', '<\2>', $page);
echo $page;

When you run it from the CLI:

$ php test.php
some text <p> another text <br> some text <br> and/or another text

See this regex101: https://regex101.com/r/9JtCxP/1. What differs from your link is that I clicked on "Substitution" on the left-hand menu and added the "g" flag.

CodePudding user response:

The reason for the error was that in the text, instead of <>, there were &lt; and &gt;. Visually there was no difference. But only visually.

  •  Tags:  
  • Related