user3396420
user3396420

Reputation: 840

Get incomplete word matched with regular expression

I have a text and I need to find words which begens with one word, and I need to get the complete word which match with this expression.

Example: I search "abc" in a text like: "Hi abc is abc123" and I need to get an array with: [0] = "abc" and [1] = "abc123" because both match with my expresion "abc".

I have this code:

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

But I get always [0] = "abc" and [1] = "abc".

How can I do this?

Upvotes: 1

Views: 60

Answers (1)

Ben
Ben

Reputation: 9001

//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]);

Will output:

Array ( [0] => abc [1] => abc123 )

Upvotes: 1

Related Questions