Reputation: 549
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
Reputation: 10466
preg_replace('/Look at the shiny apple \[\w+\]/gi','Look at the shiny apple', $subject);
should do the trick.
Upvotes: 1
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
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