开发者

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-char开发者_如何学Cacters?

For example -

Text-string before -

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

Text-string after -

"look at the shiny apple"


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 "[").


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

should do the trick.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜