1

I have the below text but want the quote bit removed from the string, I'm using the below regex but it gives me the below error.

Text Example 1

<p>[quote]</p>
<p>[quote]</p>
<p>inner quote text</p>
<p>[/quote]</p>
<p>outer quote text</p>
<p>[/quote]</p>
<p>This is a test.</p>

Text Example 2

<p>[quote][quote]</p>
<p>inner quote text</p>
<p>[/quote]</p>
<p>outer quote text</p>
<p>[/quote]</p>
<p>This is a test.</p>

Expected Text

<p>This is a test.</p>

Regex

preg_replace('/<p>\[quote\][\s\S]+?<p>\[\/quote\]<\/p>/', '', $string);

Error

Warning: preg_replace(): Compilation failed: missing terminating ] for character class at offset

I've had a look at Deleting text between two strings in php using preg_replace which has helped but I haven't been able to figure it out, any help greatly appreciated.

4
  • 2
    What should be the resulting text? Commented Feb 9, 2018 at 17:19
  • 1.) the error says you haven't escaped [ in ...\<p\>[...2.) your sample text contains [quote and not [quote]. Further there is no need to escape <,> Commented Feb 9, 2018 at 17:43
  • @mrzasa, sorry, updated the question now. Commented Feb 9, 2018 at 18:03
  • 1
    This tool will help you testing your regex (with great explanations): regex101.com Commented Feb 9, 2018 at 18:05

2 Answers 2

2

The reason you're getting the error is because you've not escaped an opening [ character in your regular expression. Please see the [ I have marked below:

preg_replace('/\<p\>\[quote\]\<\/p\>[\s\S]+?\<p\>[\/quote\]\<\/p\>/', '', $string);
                                                 ^

This has resulted in starting a character class that has not been closed. You should simply escape this opening brace like this:

preg_replace('/\<p\>\[quote\]\<\/p\>[\s\S]+?\<p\>\[\/quote\]\<\/p\>/', '', $string);
Sign up to request clarification or add additional context in comments.

Comments

0

Extracting text from HTML is tricky, so the best option is to use a library like Html2Text. It was built specifically for this purpose.

https://github.com/mtibben/html2text

Install using composer:

composer require html2text/html2text Basic usage:

$html = new \Html2Text\Html2Text('<p>[quote</p>test piece of text<p>[/quote]</p>This is a test.');

echo $html->getText();  // test piece of text This is a test.

OR you can use simply the function PHP strip_tags

string strip_tags ( string $str [, string $allowable_tags ] )

http://php.net/strip_tags

echo str_replace("[/quote]","",str_replace("[quote","",strip_tags("<p>
[quote</p>
test piece of text
<p>[/quote]</p>
This is a test.")));

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.