Swapnil
Swapnil

Reputation: 654

Multiple Hash Tags removal

function getHashTagsFromString($str){
               $matches = array();
               $hashTag=array();
                    if (preg_match_all('/#([^\s]+)/', $str, $matches)) {

                        for($i=0;$i<sizeof($matches[1]);$i++){
                                $hashtag[$i]=$matches[1][$i];
                                }
                       return $hashtag;
                      }
            }

test string $str = "STR
this is a string
with a #tag and
another #hello #hello2 ##hello3   one
STR";

using above function i am getting answers but not able to remove two # tags from ##hello3 how to remove that using single regular expression

Upvotes: 1

Views: 34

Answers (2)

anubhava
anubhava

Reputation: 785611

EDIT: To match all the hash tags use:

preg_match_all('/#\S+/', $str, $match);

To remove, instead of preg_match_all you should use preg_replace for replacement.

$repl = preg_replace('/#\S+/', '', $str);

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76636

Update your regular expression as follows:

/#+(\S+)/

Explanation:

  • / - starting delimiter
    • #+ - match the literal # character one or more times
    • (\S+) - match (and capture) any non-space character (shorthand for [^\s])
  • / - ending delimiter

Regex101 Demo

The output will be as follows:

Array
(
    [0] => tag
    [1] => hello
    [2] => hello2
    [3] => hello3
)

Demo

Upvotes: 1

Related Questions