Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match foreach

Tags:

regex

php

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.

like image 763
Sumo Avatar asked Jul 02 '11 22:07

Sumo


2 Answers

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;
}
like image 54
Francois Deschenes Avatar answered Nov 09 '22 14:11

Francois Deschenes


Check preg_match_all

like image 37
Balanivash Avatar answered Nov 09 '22 15:11

Balanivash