user2320500
user2320500

Reputation: 169

Testing for matches within a string

I have a script that grabs all of the hash tags from a string and then stores them in an array, well what happens next is determined by whether or not there are any hash tags in the string. How do I create an if statement to only run the code if there are indeed hash tags in the string being tested.

Here is what I have tried:

<?php

$string= "Went for an awesome bike";

echo $string . "</br></br>";

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


if ($matches != 0) {

    foreach ($matches[1] as $tag) {

        echo $tag . "</br></br>";

    }

}
else {

    echo "There are no tags here!!";

}


?>

I cant get it to echo out the failure message? What could I be doing wrong?

Thanks!

Upvotes: 0

Views: 47

Answers (4)

reikyoushin
reikyoushin

Reputation: 2021

the easiest way for checking is by changing your line

if ($matches != 0) {

into

if ($matches[1]) {

to check if there are matches on your string (since it will be false if the array is empty)

if you are validating, you can do var_dump($matches); to see what preg_match_all() returns

for a bonus, you can check your regex here on a testing site i use

Upvotes: 1

bwoebi
bwoebi

Reputation: 23777

var_dump(array() == 0);

=>

bool(false)

Check for:

 if (!empty($matches[0]))

as the array $matches is always filled with at least one item; but the entries of this array aren't always.

Upvotes: 0

Marc B
Marc B

Reputation: 360702

preg_match_all() will return how many matches were made (including 0), or boolean false on failure, so just a simple:

$cnt = preg_match_all(...);
if (($cnt !== FALSE) && ($cnt > 0)) {
    ... found something ...
}

will do. Note the !==. This is necessary to distinguish between a true boolean false, and a simple integer 0, both of which test as equal when using the standard non-strict == logic.

Upvotes: 1

nickb
nickb

Reputation: 59699

Matches is an array.

if ( count( $matches[1]) != 0)

Upvotes: 0

Related Questions