Get single word after each hash symbol in a string

How to explode a string, for instance

#heavy / machine gun #test

in order to only get heavy and test?

I tried with explode but so far I only got heavy / machine gun and test.

Upvotes: 3

Views: 106

Answers (3)

Emissary
Emissary

Reputation: 10148

A regular expression is obviously more robust in this case but just for laughs:

$str = '#heavy / machine gun #test';

$arr = array_filter(array_map(function($str){
    return strtok($str, ' ');   
}, explode('#', $str)));

» example

Upvotes: 0

user399666
user399666

Reputation: 19879

Alternative to explode:

$str = "#heavy / machine gun #test";
preg_match_all('/#([^\s]+)/', $str, $matches);
var_dump($matches[1]);

This will basically find all hashtags in a given string.

Upvotes: 1

Clément Malet
Clément Malet

Reputation: 5090

Re-explode your "first" part on spaces to get 'heavy' only

$heavy = explode (' ', $my_previous_explode[1]); // I guessed you exploded on '#', so array index = 1

Upvotes: 0

Related Questions