0

To sanitise user input from a WYSIWYG editor, I'm trying to find the following strings:

<p>&nbsp;</p>

<p> </p>

<p></p>

This is the regular expression I'm currently using:

/\<p\>([nbsp\;]*|[\s]*|[ ]*)\<\/p\>/i

I'm quite new to RegEx, but from what I understand, this:

  1. \<p\>: - Matches <p> exactly, then
  2. ( - Matches either:
    • [nbsp\;]* - "nbsp;" exactly, any number of times
    • |[\s]* - or any whitespace character, any number of times
    • |[ ]* - or " " (a space), any number of times
  3. <\/p\> - Matches </p> exactly

However, this expression only matches <p>nbsp;</p> and not the other two.

I have also tried:

/\<p\>[nbsp\;|\s| ]*\<\/p\>/i

I am testing it using RegEx101.com (first expression, second expression)

How can I get this to work?

4 Answers 4

1

You can't use "whole words" inside of a character class, the following will suffice ...

~<p>(?:&nbsp;|\s)*</p>~i

Note: You don't need to include <space>, the \s token will match the whitespace and you don't need to escape < and >, they are not considered special characters.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to use the g modifier for multiple matches.

/\<p\>([nbsp\;|\s| ]*[\s]*|)\<\/p\>/gi

https://regex101.com/r/zR9jY4/2

Comments

1

You forget the amp; &

 /\<p\>[&nbsp\;|\s| ]*\<\/p\>/i

In example

<p>&nbsp;</p>

<p> </p>

<p></p>
<p> asdfas</p>

This would match the first 3

Comments

0

You don't have to use square brackets.

/\<p\>(&nbsp;*|\s*)\<\/p\>/i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.