Match a single character within a string and then replace that character using Regex in PHP

I have this code:

<p><br>< br> </ strong> </ div>

So what I need is to match and replace just the "\s" or " " (empty) that is between "</" and "[a-zA-Z]+>", so basically and using "/</([ ]+)[a-z]+>/g" but it match all the chain and I'm needing for match just the single character and replace it.

By the way, now I'm using the code below to replace the empty I mean for delete the empty character. But I wanna know if that I asked is possible. Thanks.

//this code replace what I need    
$htmlfixed = preg_replace('/(?<=<\/)([ ]+)(?=[a-zA-Z]+>)/', '', $html);

Upvotes: 1

Views: 69

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

This could be one way to achieve that,

const regex = /(<\/?)[\s]/gm;
const str = `<p><br>< br> </ strong> </ div>`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

See at Regex

Upvotes: 1

Nick
Nick

Reputation: 147146

Your existing code will also delete the tag. You just need to delete the whitespace between the </ and the tag, so you can just use a regex of (?<=</)\s+ i.e. whitespace (\s+) preceded by </:

$html = '<p><br>< br> </ strong> </ div>';
$htmlfixed = preg_replace('#(?<=</)\s+#', '', $html);
echo $htmlfixed;

Output:

<p><br>< br> </strong> </div>

Demo on 3v4l.org

Upvotes: 1

Related Questions