3

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Papaa
  • 108
  • 10

2 Answers2

6

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]);
Mohammad
  • 21,175
  • 15
  • 55
  • 84
2

Personally I would not capture the word with #, since a hashtag is only an identifier for your code to get the attached word.

$re = '/(?<!\S)#([A-Za-z_][\w_]*)/';
$str = "My name's #jeff,what #0is #thy name?";

preg_match_all($re, $str, $matches);

// Print the entire match result
print_r($matches[0]); // #jeff, #thy
print_r($matches[1]); // jeff, thy

By the rules of hashtags, it may not start with a digit but may contain them.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38