How can I get the next word after pregmatch with PHP.

For example, If I have a string like this:

```
"This is a string, keyword next, some more text. keyword next-word."

```

I want to use a `preg_match` to get the next word after “keyword”, including if the word is hyphenated.

So in the case above, I want to return “next” and ”next-word”

I’ve tried :

```
$string = "This is a string, keyword next, some more text. keyword next-word.";

$keywords = preg_split("/(?<=\keyword\s)(\w+)/", $string);
print_r($keywords);

```

Which just returns everything and doesn’t seem to work at all.

Any help is much appreciated.
['https://Stackoverflow.com/questions/24226385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3143218/']
Using your example this should work using [`preg_match_all`](http://www.php.net/manual/en/function.preg-match-all.php):

```
// Set the test string.
$string = "This is a string, keyword next, some more text. keyword next-word. keyword another_word. Okay, keyword do-rae-mi-fa_so_la.";

// Set the regex.
$regex = '/(?<=\bkeyword\s)(?:[\w-]+)/is';

// Run the regex with preg_match_all.
preg_match_all($regex, $string, $matches);

// Dump the resulst for testing.
echo '<pre>';
print_r($matches);
echo '</pre>';

```

And the results I get are:

```
Array
(
    [0] => Array
        (
            [0] => next
            [1] => next-word
            [2] => another_word
            [3] => do-rae-mi-fa_so_la
        )

)

```
While regex is powerful, it's also for most of us hard to debug and memorize.

On this particular case, **Get next word after ... match with PHP**, which is a very common string operation.

Simply, by exploding the string in an array, and searching the index. This is useful because we can specify how much words forward or backward.

This match the first occurrence + `1 word`:

```
<?php
$string = explode(" ","This is a string, keyword next, some more text. keyword next-word.");
echo $string[array_search("keyword",$string) + 1];
/* OUTPUT next, *

```

[Run it online](https://3v4l.org/4bnXr)

By reversing the array, we can catch the last occurrence - `1 word`:

```
<?php
$string = array_reverse(explode(" ","This is a string, keyword next, some more text. keyword next-word."));
echo $string[array_search("keyword",$string) - 1];
/* OUTPUT next-word. */

```

[Run it online](https://3v4l.org/4o4FJ)

This is good for performances if we are making multiples searches, but of course the length of the **string must be kept short** (whole string in memory).