Killumi
Killumi

Reputation: 21

Ignore empty match php Regex

I need to replace all of the text within the tag (which is not a code). So I'm using:

preg_replace('/<.*?>([^<]*)<\/.*?>/', "new_text", $str)

And I get a result. But I need to remove all empty and onlywhitespace matches or eliminate them from the search. How can i do it?

Upvotes: 1

Views: 971

Answers (2)

A-y
A-y

Reputation: 793

I would suggest something like this :

<.*?>((?=[^<]*\S.*?<)([^<]+))<\/.*?>

or, if you want to include newlines in your match :

(<.*?>)(?=[^<]*\S.*[<\n])([^<]+)(<\/.*?>)

Here's a demo

It's similar to your awnser in replacing your matching group with [^<]+ to make sure at least one character is returned

However, to make sure that whitespace only strings won't be matched, there is a look-ahead that is added after the opening tag match :

(?=[^<]*\S.*?<)

This makes sure that between the two tags there is at least one character that isn't whitespace.

more info on lookaheads

Upvotes: 1

Killumi
Killumi

Reputation: 21

Before:

preg_replace('/<.*?>([^<]*)<\/.*?>/', "new_text", $str)

After:

Use +: preg_replace('/<.*?>([^<]+)<\/.*?>/', "new_text", $str)

Upvotes: 0

Related Questions