Jump to content

preg_replace help!


Recommended Posts

Wasn't too sure where to go with this one, but, I have preg_replace problem!This is what I have at the min..

preg_replace('/\[review id="[0-9a-zA-Z]"\](.*?)\[\/review\]/is', '<a href="review.php?id={$1}" title="Click for a review on {$2}">{$2}</a>', $str);

So for example when I input: [review id=123]Leeds Festival[/review] ..It will produce: <a href="review.php?id=123" title="Click for a review on Leeds Festival">Leeds Festival</a>But it's not changing?Can anyone help?Adam!

Link to comment
Share on other sites

You were very close, but had a few glitches. Try this:

preg_replace('/\[review id="(\w+)"\](.*?)\[\/review\]/i', '<a href="review.php?id=$1" title="Click for a review on $2">$2</a>', $str);

First, we needed 2 sets of captures, since you use 2 back references. So I added a set of parens.Second, I used a shortcut for [0-9a-zA-Z], which is simply \w (which means "word" character). Technically, this includes the underscore character, but I'm guessing that won't make a difference.Third, I got rid of the curly braces, which you were using incorrectly. The correct syntax is ${1}, but it's only needed if the back reference is immediately followed by a digit, as in ${1}1, which would otherwise be mistaken for $11. Since you don't even need that, let's just chuck them.Most important, I added the + to the first capture so it would recognize multiple characters in the first capture.Oh yeah, I took out the s modifier. Do you need to match a newline character?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Create New...