user2320500
user2320500

Reputation: 169

Getting hash tagged words from a string with PHP

I am trying to create an array of all of the hash tags in a given string and then loop through them and echo each one to show that they have been stored. What could I be doing wrong?

<?php

    $string= "Went for an awesome bike ride today! #biking";

    preg_match_all('/#(\w+)/',$string, $matches);

        foreach ($matches as $tag) {

            echo $tag;

        }

?>

Upvotes: 0

Views: 90

Answers (1)

bwoebi
bwoebi

Reputation: 23777

    foreach ($matches[1] as $tag) {
        echo $tag;
    }

is only outputting your matches.

$matches is a array with as many entries as you have parenthesis in your regex plus one.

See also: http://3v4l.org/MJCWE

Upvotes: 2

Related Questions