Sumo
Sumo

Reputation: 73

preg_match foreach

So I am using a preg_match to get any text after a # up until a space out of a string. However if there are multiple occasions of it in the string it will only return the first one. This is what I have so far

$text = '#demo1 #demo2 some text #blah2';
$check_hash = preg_match("/([#][a-zA-Z-0-9]+)/", $text, $hashtweet);
foreach ($hashtweet as $ht){
echo $ht;
}

The echo $ht; outputs #demo1#demo1 when it should output all 3 of the words with # in front. Any help is greatly appreciated.

Upvotes: 7

Views: 17990

Answers (2)

Balanivash
Balanivash

Reputation: 6867

Check preg_match_all

Upvotes: 1

Francois Deschenes
Francois Deschenes

Reputation: 24989

You want to use preg_match_all.

Example:

<?php 

$text = '#demo1 #demo2 some text #blah2';
$check_hash = preg_match_all("/([#][a-zA-Z-0-9]+)/", $text, $hashtweet);
foreach ($hashtweet[1] as $ht){
  echo $ht;
}

Upvotes: 17

Related Questions