获得与正则表达式匹配的不完整单词

时间:2016-01-26 15:08:15

标签: php preg-match

我有一个文字,我需要找到一个单词的begens,我需要得到与这个表达式匹配的完整单词。

实施例: 我在"abc"这样的文字中搜索"Hi abc is abc123",我需要使用[0] = "abc" and [1] = "abc123"获取一个数组,因为它们都与我的表达式"abc"匹配。

我有这段代码:

$words = [];
    foreach($items as $i){
        $text = $l->getText();
        preg_match('*'."#".$q.'*', $text, $words[]);
    }

但我总是[0] = "abc" and [1] = "abc"

我该怎么做?

1 个答案:

答案 0 :(得分:1)

//Regular expresson to find: 'abc', followed by any 
//characters, until a whitespace character
$re = "/(abc[^\\s]*)/"; 

//String to search
$str = "Hi abc is abc123"; 

//Find all matches (/g)
preg_match_all($re, $str, $matches);

//Show matches in array
print_r($matches[0]);

将输出:

  

数组([0] => abc [1] => abc123)

相关问题