0

I have a string The Incredible Hulk (2008) and use pattern

/^\([0-9]{1,4}\)$/

to remove (2008). PHP code looks like this:

$x = trim(preg_replace("/^\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

And the result is:

The Incredible Hulk (2008)

What am I doing wrong?

5 Answers 5

4

You're using the ^ character that matches start of line. Remove that and it should work.

If you also want to get rid of the whitespace before the ( the regex becomes /\s*\([0-9]{1,4}\)$/

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

Comments

2

Take out "^".

$x = trim(preg_replace("/\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

The (2008) is not anchored at the start of the string. "^" requires the match to start at the beginning of a line.

Comments

1

^ and $ are mark begin and end of the entire string. Remove both.

$x = trim(preg_replace("/\([0-9]{4}\)/", "", "The Incredible Hulk (2008)"));

Comments

1

Just remove the ^ sign (beginning of line).

$x = trim(preg_replace("/\([0-9]{1,4}\)$/", "", "The Incredible Hulk (2008)"));

(you might want to remove the $ sign as well (end of line))

More info about PHP meta characters in the documentation: http://www.php.net/manual/en/regexp.reference.meta.php

Comments

0
$result = preg_replace('/\([\d]{4}\)$/', '', 'The Incredible Hulk (2008)');

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.