检查在字符串中找到的位置是否在锚点中

Check if a position found in a string is in anchors

我不知道这是否可能,但我需要测试找到的位置是否在锚点内 [a ... /a]

例如我有这个字符串:

Urna cursus condimentum aliquam cursus [a href="/l.-da-vinci"]Leonardo da Vinci[/a]turpis class tempor suscipit egestas est praesent

我有一个找位置的功能,但如果它在锚点内,我不能接受这个位置[a ... /a]

比如函数return位置48也就是l.-da-vinci中的点,那我一定不能接受。

可能吗?

一种方法是使用 preg_match()PREG_OFFSET_CAPTURE 标志,这将 return 除了匹配本身之外的匹配的起始位置。

然后您可以根据匹配的长度计算结束位置以获得锚点的范围。之后只需检查位置是否在该范围内即可:

$position = 48;
$string = 'Urna cursus condimentum aliquam cursus [a href="/l.-da-vinci"]Leonardo da Vinci[/a]turpis class tempor suscipit egestas est praesent';

preg_match('~\[a.*?\[/a\]~', $string, $matches, PREG_OFFSET_CAPTURE);

$matchStart = $matches[0][1];
$matchEnd = $matchStart+strlen($matches[0][0]);

if ($position > $matchStart && $position < $matchEnd) {
    echo 'not allowed';
} else {
    echo 'allowed';
}

https://3v4l.org/INCh1