PHP Regex: Matching Ands - & and &

回眸只為那壹抹淺笑 提交于 2021-02-10 08:06:41

问题


I am trying to matching and characters from html. There are three types of ands:

and, &, &

I'm using the following code:

(&|&|\band\b)

The problem with above code is: it also matches words which start with &

i.e. © €

I've also tried the following, but it does not match & character from the start and end of line in the text.

(\s&\s|&|\band\b)

回答1:


How about

(&)|&(?!\w)|\band\b

Matches and, &, &

Does not match © €

The middle one matches an ampersand that is not followed by a word character ([A-Za-z0-9_])




回答2:


(&|&|\band\b)

is a good start. Go on by reducing the result set, you will have to specify details when not to match. There is no magic delimiter that tells a regex what you want. So the question is: how can you tell the '&' you want to accept from those you do not want to accept ?

Maybe you want to accept all '&' if not starting a word ? So:

(&[^a-zA-Z]|&|\band\b)



回答3:


Try this regex :

$regex = '/\b((\&(amp;)?)|(and))\b/i';


来源:https://stackoverflow.com/questions/11768004/php-regex-matching-ands-and-amp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!