Belgin Fish
Belgin Fish

Reputation: 19827

PHP Regex to match words with dash right infront and save to array?

i'm wondering what kind of regex I could use to essentially extract all the words that have a dash infront of them in a given string. I'm going to be using it to allow users to omit certain words from the search results of my website.

For example, say I have

$str = "this is a search -test1 -test2";

I'm trying to have it save "test1" and "test2" to an array because they have a dash right infront.

Could anyone help me out

Upvotes: 0

Views: 849

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

this do the job:

<pre><?php    
$string = 'Phileas Fog, Passe-Partout -time -day -@StrAn-_gE+*$Word²²²';
preg_match_all('~ -\K\S++~', $string, $results);
print_r($result);

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157927

Use the following pattern /\-(\w+)/. Example:

$string = 'this is a search -test1 -test2';
$pattern = '/\-(\w+)/';
if(preg_match_all($pattern, $string, $matches)) {
    $result = $matches[1];
}
var_dump($result);

Output:

array(2) {
  [0] =>
  string(5) "test1"
  [1] =>
  string(5) "test2"
}

Explanation:

/.../ delimiter chars

\-    a dash (must be escaped as it has a special meaning in the regex language

(...) special capture group. stores the content between them in $matches[1]

\w+   At least one ore more word characters

Upvotes: 3

Related Questions