I'm looking for php code to split word from text using regex, preg_match()
, preg_split()
, or any other way.
$textstring="one #two three #four #five";
I need to get #two
,#four
, and #five
saved as array elements.
Try splitting by this: \b #
preg_split("/\\b #/", $text)
Try this:
$text="one #two three #four #five";
$parts = array_filter(
explode(' ', $text), // split into words
function($word) {
// filter out all that don't start with '#' by keeping all that do
return strpos($word,"#")===0;
// returns true when the word starts with "#", false otherwise
}
);
print_r($parts);
You can see it here: https://3v4l.org/YBnu3
You may also want to read up on array_filter
Use a negated character class after the #
symbol for highest pattern efficiency:
Pattern: (Demo)
#[^ ]+ #this will match the hashtag then one or more non-space characters.
Code: (Demo)
$in='one #two three #four #five';
var_export(preg_match_all('/#[^ ]+/',$in,$out)?$out[0]:'failed'); // access [0] of result
Output:
array (
0 => '#two',
1 => '#four',
2 => '#five',
)