查找字符串中的最后一个单词,没有任何点,空格

时间:2013-07-10 19:10:52

标签: preg-match

我不理解正则表达式,因为它看起来非常困难......所以我发现它只是用点等找到最后一个单词。

$content='Nullam quis risus eget urna mollis ornare vel eu leo.';
$pattern = '/[^ ]*$/';
preg_match($pattern, $content, $result);
echo $result[0];

我得到了“狮子座。”。

如何才能获得“leo”,没有点或问号?

谢谢。

3 个答案:

答案 0 :(得分:1)

您可以使用$锚点和前瞻来获取最后一个单词:

$pattern = '~[a-z]+(?=[^a-z]*$)~i';

说明:

~           # pattern delimiter
 [a-z]+     # all characters between a and z (included) one or more times
 (?=        # open a lookahead. Means followed by:
    [^a-z]* # all characters that are not letters zero or more times
    $       # until the end of the string
 )          # close the lookahead
~           # pattern delimiter
i           # case insensitive ( [a-z] => [a-zA-Z] and [^a-z] => [^a-zA-Z])

对于你的正则表达式尝试,我建议你使用这个特定于php的online tool

答案 1 :(得分:0)

您可以使用rubular.com来学习和测试正则表达式。他们还提供了一个很好的作弊表=)。

你会听到你的话:\ b([a-zA-Z] *)[\ W] $

使用此正则表达式,您也将匹配该点。要仅提取“leo”,您需要了解捕获组:http://www.regular-expressions.info/named.html

答案 2 :(得分:0)

不知怎的,我用模式解决了这个问题:'/ [\ p {L} \ d] +(?= [^ a-z] * $)/ u'。也许有人知道如何在字符串中找到第一个和最后一个单词并将它们放入,带有preg_match的数组?