1

If I have a string like

$str = "Hello [Page 1] World [Page 23] Hello [Page 35] World [Page 624]";

And I want to remove all instances of "[Page #]"

How would I go about doing that?

Here's what I've got so far...

preg_replace('[Page [0-9]]', '', $str);

3 Answers 3

1

Remember that [ and ] are class delimiters. When you want to use them as literals you need to escape them (prefix with \) first. So:

/\[Page [0-9]+\]/i

is probably your best bet. Surround the pattern with /, add a + to your number range to match "1+ numbers", and the final i means case-insensitive match (P or p in "Page") (remove if that's not your intent).

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

Comments

0
preg_replace('/\\[Page [0-9]+\\]/', '', $str)

3 Comments

need to escape the [ to match them. the plus means one or more.
You also need to add a delimiter eg /pattern/ or @pattern@
and double escape to get the escape into the pattern. corrected the answer.
0
/\[Page \d+\]/

works, too. \d is shorthand for number-chars.

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.