How to "preg_match" only numbers?

Asked

Viewed 1,327 times

2

My attempt, a failure:

$post_id = preg_match("/^[0-9]+$/", $_POST['post_id']);

I tried to be a user who changed the id of the post to for example: post_id="43223646", However, when the data is entered into mysql, they are transformed into the number 1, how to make it work properly?

  • I suggest looking at the documentation of preg_match. It returns 1 or 0. You would have to use the third parameter

  • how to make it work properly?

1 answer

4


The preg_match PHP returns 1 if the expression matched, 0 if it did not match and false if an error has occurred.

In your case, it’s returning 1 because it’s matching.

But as you want the value itself, you must use the third parameter:

pouch
If Matches is provided, it will be filled with the search results.

Do so:

preg_match("/^[0-9]+$/", $_POST['post_id'], $matches);
$post_id = $matches[0];

Documentation

  • thanks =D, WORKED PERFECTLY

Browser other questions tagged

You are not signed in. Login or sign up in order to post.