Pattern for check single occurrency into preg_matc

2019-08-03 05:59发布

问题:

I'm writing a function that should retrieve all occurrences that I pass. I'm italian so I think that I could be more clear with an example. I would check if my phrase contains some fruits.

Ok, so lets see my php code:

$pattern='<apple|orange|pear|lemon|Goji berry>i';
$phrase="I will buy an apple to do an applepie!";

preg_match_all($pattern,$phrase,$match);

the result will be an array with "apple" and "applepie".

How can I search only exact occurency? Reading the manual I found: http://php.net/manual/en/regexp.reference.anchors.php

I try to use \A , \Z , ^ and $ but no one seems to work correctly in my case!

Someone can help me?

EDIT: After the @cris85 's answer I try to improve my question ... My really pattern contains over 200 occorrency and the phrase is over 10000 caracters so the real case is too large to insert here.

After some trials I found an error on the occurrency "microsoft exchange"! There is some special caracters that I must escape? At the moment I escape "+" "-" "." "?" "$" and "*".

回答1:

The anchors you tried to use are for the full string, not per word. You can use word boundaries to match individual words. This should allow you to find only complete fruit matches:

$pattern='<\b(?:apple|orange|pear|lemon|Goji berry)\b>i';

The ?: is so you don't make an additional capture group, it is a non-capture group.

Here's the definitation from regex-expressions for what a boundary matches:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

PHP Demo: https://3v4l.org/h5GCf

Regex Demo: https://regex101.com/r/5aBaMO/1/