查找句点之前的所有字母数字字符串

Find all alphanumerical strings before a period

如何检索非字母数字或下划线与句点之间的所有字符串?例如,对于下面的字符串,得到 [sources_1st,sources]。 是一个类似的问题,但似乎对我不起作用。

<?php

function check($pattern,$str)
{
    echo($pattern.'<br>');
    preg_match($pattern, $str, $matches);
    echo('<pre>'.print_r($matches,1).'</pre>');    
}
$str='fullname("protocol",coalesce(sources_1st.protocol,sources.protocol))';
echo($str.'<hr>');

check('/[^.]+\.[^.]+$/',$str);
check('/[\w]\..*$/',$str);
check('/[^\w]\..*$/',$str);
check('/\w\..*$/',$str);
check('/\w+(?=.*\.)$/',$str);
check('/\w+(?=.*\.)$/',$str);
check('/\b[^ ]+\.$/',$str);
check('/\b[^ ]+\.$/',$str);
check('/.*?(?=\.)$/',$str);

输出:

fullname("protocol",coalesce(sources_1st.protocol,sources.protocol))
--------------------------------------------------------------------------------
/[^.]+\.[^.]+$/

Array
(
    [0] => protocol,sources.protocol))
)

/[\w]\..*$/

Array
(
    [0] => t.protocol,sources.protocol))
)

/[^\w]\..*$/

Array
(
)

/\w\..*$/

Array
(
    [0] => t.protocol,sources.protocol))
)

/\w+(?=.*\.)$/

Array
(
)

/\w+(?=.*\.)$/

Array
(
)

/\b[^ ]+\.$/

Array
(
)

/\b[^ ]+\.$/

Array
(
)

/.*?(?=\.)$/

Array
(
)

使用下面的正则表达式,您可以在非单词字符和句点之间匹配单词字符:

\W\K\w+(?=\.)

Live demo

解释:

  1. \W 匹配一个非单词字符
  2. \K 丢弃上一场比赛
  3. \w+(?=\.) 句点以内的任何单词字符

PHP代码:

preg_match_all('~\W\K\w+(?=\.)~', $str, $matches)