Search code examples
phpregexstringpreg-matchpreg-match-all

How to get the words that start with '#' in string using php?


I have this sentence

"My name's #jeff,what is thy name?"

And now i want to get #jeff from this sentence. I have tried this code

for ($i=0; $i <=substr_count($Text,'#'); $i++) { 
    $a=explode('#', $Text);
    echo $a[$i];
}

But it returns #jeff,what is thy name? which is not what my soul desires


Solution

  • There is simpler solution to do it. Use preg_match() that find target part of string using regex.

    preg_match("/#\w+/", $str, $matches);
    echo $matches[0]
    

    Check result of code in demo

    If you want to get all matches string, use preg_match_all() that find all matches.

    preg_match_all("/#\w+/", $str, $matches);
    print_r($matches[0]);