Marko Vasic
Marko Vasic

Reputation: 690

search for pattern in string and echo if find it

I have a following problem: I need to check if string contains any pattern string and echo the result if it does.

$searching_post = preg_match("/#([0-9]{3,8})/", $_POST['Description']);

this will return 1 if it contain pattern, but I would like to return that result instead one. So if $_POST['Description'] contain for example #123 I want to return #123 instead 1. Anyone know how to do that?

Upvotes: 0

Views: 204

Answers (1)

h2ooooooo
h2ooooooo

Reputation: 39550

If you look at the manual for preg_match you'll figure out that it puts the matches into a referenced variable in the 3rd parameter:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )


preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.


So the code should be something like the following:

$searching_post = null;
if (preg_match("/#([0-9]{3,8})/", $_POST['Description'], $matches)) {
    $searching_post = $matches[1];
}
var_dump($searching_post); //will be NULL if nothing was found

Upvotes: 2

Related Questions