Wes
Wes

Reputation: 549

How to use regex in php for phrase containing meta-characters?

Anyone know how to use a php regex to remove text from a string that contains regex meta-characters?

For example -

Text-string before -

"Look at the shiny apple [word]" //where 'word' could be anything

Text-string after -

"look at the shiny apple"

Upvotes: 0

Views: 416

Answers (3)

Jesse
Jesse

Reputation: 10466

preg_replace('/Look at the shiny apple \[\w+\]/gi','Look at the shiny apple', $subject);

should do the trick.

Upvotes: 1

stema
stema

Reputation: 93006

You replace something with regex using preg_replace.

If you want to match a special character literally you have to escape the character in the regular expression using a backslash like this \[ (if you want to match a "[").

Upvotes: 1

Howard Lince III
Howard Lince III

Reputation: 342

Your regex would look something like this:

"(?<=Look at the shiny apple )\S*"

The (?<=) is a positive lookbehind, it says it must exist before the match, but not to include it in the match.

This is a good tool for testing and figuring out regex: http://www.gskinner.com/RegExr/

Edit: as noted below, without a space after the .* it would match the rest of the data, \S could also be used. Thanks Jesse

Upvotes: 0

Related Questions